704.二分查找
网络异常,图片无法展示
|
#include <iostream> #include <vector> using namespace std; class Solution { public: int search(vector<int>& nums, int target) { int left=0, right=nums.size(); int middle = 0; while (1) { middle = (left + right) / 2; if (target == nums[middle]) return middle; else if (target > nums[middle]) left = middle + 1; else right = middle ; if (left >= right) return -1; } } }; int main() { vector<int> my_nums = { -1,0,3,5,9,12 }; int my_target = 12; Solution a; cout << a.search(my_nums,my_target); return 0; }
二刷
class Solution { public: int search(vector<int>& nums, int target) { int result=-1; int left=0; int right= nums.size()-1; while(left <= right) { int mid = (right + left)/2; if(nums[mid]==target) { result = mid; break; } else if(nums[mid]>target) right = mid-1; else if(nums[mid]<target) left = mid +1; } return result; } };