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