leetcode-剑指57-OK

language: C

address

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
// 寻找第一个数的时候,遍历整个数组,然后为它找第二个数
// 找第二个数的时候使用二分查找
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
    returnSize[0] = 2;
    int i;
    int *ans= (int *)malloc(sizeof(int) *2);
    bool flag =false;
    void fill(int m,int n){
        ans[0] = m;
        ans[1] = n;
        flag = true;
    }
    for( i = 0; i<numsSize-1;  i++){
        if (flag)
            break;
        int low= i+1,high = numsSize-1;
        int mid;
        while((low<=high)&&(!flag)){
            mid = (low + high)/2;
            if (nums[i]+nums[mid]==target)
                fill(nums[i],nums[mid]);
            else if(nums[i]+nums[mid]>target)
                high = mid-1;
            else if(nums[i]+nums[mid]<target)
                low = mid +1;
        }
    }
    return ans;
}
posted @ 2021-01-25 07:33  RougeBW  阅读(30)  评论(0编辑  收藏  举报