[leetcode]704. Binary Search

[leetcode]704. Binary Search


Analysis

年纪大了就会比较惜命~—— [ummmm~]

Given a sorted (in ascending order) integer array nums of n elements and a target value, write a function to search target in nums. If target exists, then return its index, otherwise return -1.
简单的二分查找~

Implement

class Solution {
public:
    int search(vector<int>& nums, int target) {
        int len = nums.size();
        int left = 0;
        int right = len-1;
        int mid;
        while(left <= right){
            mid = left+(right-left)/2;
            if(nums[mid] == target)
                return mid;
            else if(nums[mid] > target)
                right = mid-1;
            else
                left = mid+1;
        }
        return -1;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_32135877/article/details/81168157