Last active
July 18, 2022 08:05
-
-
Save icameling/dfb2fe6ddb21612c39a96251cfdacae9 to your computer and use it in GitHub Desktop.
#数组 #二分查找 #leetcode
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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