704. Binary Search easy题
为啥我写二分法跑得比暴力解还慢啊
我有写错吗
:(
暴力法:
class Solution {
public:
int search(vector<int>& nums, int target) {
for(int i=0; i<nums.size(); i++){
if(nums[i]==target) return i;
}
return -1;
}
};
二分法:
class Solution {
public:
int search(vector<int>& nums, int target) {
int left = 0;
int right = nums.size() - 1;
int mid = (left+right)/2;
while(left<=right){
if(target == nums[mid]) return mid;
if(target < nums[mid]) {
right = mid - 1;
mid = (left+right)/2;
continue;
}
if(target > nums[mid]) {
left = mid + 1;
mid = (left+right)/2;
continue;
}
}
return -1;
}
};