Skip to content

Instantly share code, notes, and snippets.

@icameling
Last active July 18, 2022 08:05
Show Gist options
  • Save icameling/dfb2fe6ddb21612c39a96251cfdacae9 to your computer and use it in GitHub Desktop.
Save icameling/dfb2fe6ddb21612c39a96251cfdacae9 to your computer and use it in GitHub Desktop.
#数组 #二分查找 #leetcode
class Solution {
public:
int search(vector<int>& nums, int target) {
if (nums[0] > target || nums.back() < target)
return -1;
int left = 0, right = nums.size() - 1;
// [left, right]
while (left <= right) {
int mid = left + (right - left) / 2;
if (target < nums[mid]) {
right = mid - 1; // [left, mid-1]
} else if (target > nums[mid]) {
left = mid + 1; // [mid+1, right]
} else if (target == nums[mid]) {
return mid;
}
}
return -1;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment