LeetCode 704 Binary Search 模板


Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return /(-1/).

You must write an algorithm with /(O(/log n)/) runtime complexity.

Solution

点击查看代码
class Solution {
public:
    int search(vector<int>& nums, int target) {
        int n = nums.size();
        if(n==1){
            if(nums[0]==target)return 0;
            else return -1;
        }
        int l=0,r=n-1;
        int mid;
        while(l<r){
            mid = (l+r)>>1;
            if(nums[mid]<target)l=mid+1;
            else if(nums[mid]==target)return mid;
            else r=mid;
        }
        if(nums[r]!=target)return -1;
        else return r;
    }
};

原创文章,作者:254126420,如若转载,请注明出处:https://blog.ytso.com/274701.html

(0)
上一篇 2022年7月16日
下一篇 2022年7月16日

相关推荐

发表回复

登录后才能评论