LeetCode算法入门(第四十九天)
二分查找
34.在排序数组中查找元素的第一个和最后一个位置
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int leftBorder = getLeftBorder(nums, target);
int rightBorder = getRightBorder(nums, target);
if (leftBorder == -2 || rightBorder == -2) return {-1, -1};
if (rightBorder - leftBorder > 1) return {leftBorder + 1, rightBorder - 1};
return {-1, -1};
}
private:
int getRightBorder(vector<int>& nums, int target) {
int left = 0;
int right = nums.size() - 1;
int rightBorder = -2;
while (left <= right) {
int middle = left + ((right - left) / 2);
if (nums[middle] > target) {
right = middle - 1;
} else {
left = middle + 1;
rightBorder = left;
}
}
return rightBorder;
}
int getLeftBorder(vector<int>& nums, int target) {
int left = 0;
int right = nums.size() - 1;
int leftBorder = -2;
while (left <= right) {
int middle = left + ((right - left) / 2);
if (nums[middle] >= target) {
right = middle - 1;
leftBorder = right;
} else {
left = middle + 1;
}
}
return leftBorder;
}
};
33.搜索旋转数组
旋转后,总会存在某一部分是有序的
class Solution {
public:
int search(vector<int>& nums, int target) {
int left = 0, right = nums.size() - 1;
while(left < right) {
int mid = left + (right - left) / 2;
if(nums[mid] >= nums[left]) {
if(target >= nums[left] && target <= nums[mid]) {
right = mid;
} else {
left = mid + 1;
}
} else {
if(target >= nums[mid] && target <= nums[right]) {
left = mid;
} else {
right = mid - 1;
}
}
}
return nums[left] == target ? left : -1;
}
};
74.搜索二维矩阵
class Solution {
public:
bool searchMatrix(vector<vector<int>> matrix, int target) {
if(matrix.size() == 0)
return false;
int row = 0, col = matrix[0].size()-1;
while(row < matrix.size() && col >= 0){
if(matrix[row][col] < target)
row++;
else if(matrix[row][col] > target)
col--;
else
return true;
}
return false;
}
};
|