LeetCode1, two numbers and (c language)

Subject description:

Given an integer array nums and a target value target, and ask you to identify the target value of the two integers in the array, and return to their array subscript.

You can assume that each input corresponds to only one answer. However, you can not re-use the same array element.

Example:

Given nums = [2, 7, 11, 15], target = 9

Because nums [0] + nums [1 ] = 2 + 7 = 9
is returned [0, 1]

Source: stay button (LeetCode)
Link: //leetcode-cn.com/problems/two-sum: https
given handler so on leetcode given by topic Writing Function Parameters

#include<stdio.h>
int* twoSum(int* nums, int numsSize, int target, int* returnSize);
int main()
{
	int arr[4] = {2,7,11,15};
	int len = sizeof(arr) / 4;
	int target;
	printf("请输入目标值:\n");
	scanf("%d",&target);
	int *returnsize;
	int *r =  twoSum(arr, len, target, returnsize);
	printf("[%d,", r[0]);
	printf("%d]", r[1]);
} 
int* twoSum(int* nums, int numsSize, int target, int *returnSize)
{
	//遍历数组找target 
	static int a[2] = {0};
	for(int i = 0; i < numsSize -1; i++)
	{
		for(int j = i + 1; j < numsSize; j++)
		{
			if(nums[i] + nums[j] == target)
			{
					a[0] = i;
					a[1] = j; 
					*returnSize = 2; //代表返回数组的大小 
					return a;
			}	
		}	
	}
	*returnSize = 0;
	return a;
} 

I this approach should be the most easy to occur, the simple time complexity is violent O (n ^ 2), a constant level of spatial complexity O (1); after expect good writing again added.

I am white, just take this to record their own learning process, the inadequacies of more exchanges.

Released nine original articles · won praise 3 · Views 2497

Guess you like

Origin blog.csdn.net/mglcms/article/details/104605683