当前位置:网站首页>Leetcode-1: sum of two numbers

Leetcode-1: sum of two numbers

2022-07-27 15:45:00 FA FA is a silly goose

subject : Given an array of integers nums And an integer target value target, Please find... In the array And is the target value target the Two Integers , And return their array subscripts .

You can assume that each input corresponds to only one answer . however , The same element in the array cannot be repeated in the answer .

You can return the answers in any order .

Example 1:

 Input :nums = [2,7,11,15], target = 9
 Output :[0,1]
 explain : because  nums[0] + nums[1] == 9 , return  [0, 1] .

Example 2:

 Input :nums = [3,2,4], target = 6
 Output :[1,2]

Example 3:

 Input :nums = [3,3], target = 6
 Output :[0,1]

Tips :

  • 2 <= nums.length <= 104
  • -109 <= nums[i] <= 109
  • -109 <= target <= 109
  • There will only be one valid answer

Advanced : You can come up with a time complexity less than O(n2) The algorithm of ?

Code

/** * Note: The returned array must be malloced, assume caller calls free(). */
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
    
  for (int i = 0; i < numsSize; i++) {
    
        for (int j = i + 1; j < numsSize; j++) {
    
            if (nums[i] + nums[j] == target) {
    
                int *ret =(int*)malloc(sizeof(int) * 2);
                ret[0] = i;
                ret[1] = j;
                *returnSize = 2;
                return ret;
            }
        }
    }
    *returnSize = 0;
    return NULL;
}

analysis :1. Function return type is int*, From the prompt , It returns an array , The parameters in the function are the address of the first element of the input array 、 Enter the number of elements in the array 、 The target 、 Returns the number of array elements ( The number of returned array elements is int * type , because int Type cannot be taken back ).

2. Use two layers for Loop to complete the sum of any two numbers in the array and compare with the target value , Open up space in the cycle , Used to store the corresponding array subscript .

原网站

版权声明
本文为[FA FA is a silly goose]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/208/202207271426526335.html