class Solution { public: int search(vector<int>& nums, inttarget) { int l = 0, r = nums.size() - 1; while(l <= r) { int mid = (l + r) / 2; if(nums[mid] < target) l = mid + 1; elseif(nums[mid] > target) r = mid - 1; else return mid; } return -1; } };
其中,变形题可根据不同的判断条件进行判断,如将三种情况重新分成两种等
lower_bound和upper_bound的实现
lower_bound—返回第一个 大于等于 的元素
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
class Solution { public: int search(vector<int>& nums, inttarget) { int l = 0, r = nums.size() - 1; int ans = -1; while (l <= r) { int mid = (l + r) / 2; if (nums[mid] >= target) { r = mid - 1; // 可能左边还有值等于target的元素 ans = mid; } else l = mid + 1; } return ans; } };
class Solution { public: int search(vector<int>& nums, inttarget) { int l = 0, r = nums.size() - 1; int ans = -1; while (l <= r) { int mid = (l + r) / 2; if (nums[mid] <= target) l = mid + 1; else { r = mid - 1; ans =mid; } } return ans; } };
class Solution { public: int minSubArrayLen(inttarget, vector<int>& nums) { long long sum = 0; int i = 0; int res = nums.size() + 1; for(int j = 0; j < nums.size(); j++) { sum += nums[j]; while(sum >= target) { res = min(res, j - i + 1); sum -= nums[i]; i++; } } return res == nums.size() + 1? 0 : res; } };
boolcheck() { for (constauto & it : store) { if ((vis.find(it.first) == vis.end()) || (vis.find(it.first) != vis.end() && vis[it.first] < it.second)) returnfalse; } returntrue; } string minWindow(string s, string t){
for (auto c : t) { store[c]++; } int i = 0, j = 0; int res = s.size() + 1; int ind = i; while (j < s.size()) { vis[s[j]]++; while (check()) // 已覆盖t字符串,则尝试缩小左边范围 { if(res > j - i + 1) { res = j - i + 1; ind = i; } vis[s[i++]]--; } j++; } return res == s.size() + 1 ? "" : s.substr(ind, res); } };
class Solution { public: vector<int> spiralOrder(vector<vector<int>>& matrix) { vector<int> res; int m = matrix.size(), n = matrix[0].size(); int up = 0, down = m-1, left = 0, right = n-1; while (up <= down && left <= right) { for (int j = left; j <= right; j++) { res.push_back(matrix[up][j]); } up++; for (int i = up; i <= down; i++) { res.push_back(matrix[i][right]); } right--; if(up > down || left > right) break; for (int j = right; j >= left; j--) { res.push_back(matrix[down][j]); } down--; for (int i = down; i >= up; i--) { res.push_back(matrix[i][left]); } left++; } return res; } };