Likou 167. Sum of Two Numbers II-Input an ordered array (binary search)

167. Sum of Two Numbers II-Input Ordered Array

Given an integer array numbers arranged in ascending order, please find two numbers from the array that satisfy the sum of the target number target.

The function should return the subscript values ​​of these two numbers in the form of an integer array of length 2. The subscript of numbers starts counting from 1, so the answer array should satisfy 1 <= answer[0] <answer[1] <= numbers.length.

You can assume that each input only corresponds to a unique answer, and you cannot reuse the same elements.

示例 1:

输入:numbers = [2,7,11,15], target = 9
输出:[1,2]
解释:2 与 7 之和等于目标数 9 。因此 index1 = 1, index2 = 2 。
示例 2:

输入:numbers = [2,3,4], target = 6
输出:[1,3]
示例 3:

输入:numbers = [-1,0], target = -1
输出:[1,2]
 

提示:

2 <= numbers.length <= 3 * 104
-1000 <= numbers[i] <= 1000
numbers 按 递增顺序 排列
-1000 <= target <= 1000
仅存在一个有效答案

answer:

As we all know, searching for ordered arrays often uses dichotomy to reduce time complexity.
So this problem can be solved using binary search.

This question is not the same as the traditional dichotomy. This question is to find two numbers , the sum of which is the target, which is the target element.
So we can convert to the traditional dichotomy , that is, randomly select an element as one of the elements that make up the target , and then use the dichotomy to find the element whose value is the target-originally selected element in the original array . If it is found directly, then output That's it; if it is not found, then we can redefine another element as the constituent element of the target, and then look for it until it is found.

Code:

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* twoSum(int* numbers, int numbersSize, int target, int* returnSize){
    
    
    int*arr = (int*)malloc(sizeof(int)*2);
    int temp = 0;
    *returnSize = 2;
    for(int i=0;i<numbersSize;i++)
    {
    
    
        temp = numbers[i];//选择的待定元素
        int left = i+1;
        int right = numbersSize-1;
        int mid ;
        while(left<=right)
        {
    
    
            mid = left+(right-left)/2;
            if(numbers[mid]>target-temp)
            {
    
    
                right = mid-1;//舍去,因为mid不符合
            }
            else if(numbers[mid]<target-temp)
            {
    
    
                left = mid+1;//同理
            }
            else if(numbers[mid]==target-temp)
            {
    
    
                arr[0] = i+1;
                arr[1] = mid+1;
                return arr;
            }
        }
    }
    return 1;
}

Guess you like

Origin blog.csdn.net/xiangguang_fight/article/details/115097229