leetcode-704.二分查找

阅读 46

2022-03-18

https://leetcode-cn.com/problems/binary-search/submissions/

二分查找:

        时间复杂度:O(log⁡n),其中 n 是数组的长度。

        空间复杂度:O(1)。

int search(int* nums, int numsSize, int target){
    int low=0,high=numsSize-1;
    int middle=(low+high)/2;
    while(low<=high){
        if(nums[middle]>target) high=middle-1;
        else if(nums[middle]<target) low=middle+1;
        else return middle;
        middle=(low+high)/2;
    }
    return -1;
}

精彩评论(0)

0 0 举报