其他分享
首页 > 其他分享> > LeetCode 704 Binary Search 模板

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;
    }
};

标签:Binary,Search,return,target,nums,704,mid,write,int
来源: https://www.cnblogs.com/xinyu04/p/16483243.html