35. 搜尋插入位置
https://leetcode.cn/problems/search-insert-position/description/?envType=study-plan-v2&envId=top-100-liked
public int searchInsert(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
while (left <= right){
int index = left + ((right - left) >> 1);
if (nums[index] == target){
return index;
}else if (target > nums[index]){
left = index + 1;
}else {
right = index - 1;
}
}
return left;
}
74. 搜尋二維矩陣
https://leetcode.cn/problems/search-a-2d-matrix/description/?envType=study-plan-v2&envId=top-100-liked
public boolean searchMatrix(int[][] matrix, int target) {
int m = matrix.length - 1;
int n = matrix[0].length - 1;
int i = 0;
int j = n;
while (i <= m && j >= 0){
if (matrix[i][j] == target){
return true;
}else if (target > matrix[i][j]){
i++;
}else {
j--;
}
}
return false;
}
總結:從右上角開始二分查詢
34. 在排序陣列中查詢元素的第一個和最後一個位置
https://leetcode.cn/problems/find-first-and-last-position-of-element-in-sorted-array/description/?envType=study-plan-v2&envId=top-100-liked
public int[] searchRange(int[] nums, int target) {
int i = 0;
int j = nums.length - 1;
int left = -1,right = -1;
while (i <= j){
int index = i + ((j - i) >> 1);
if (target == nums[index]){
left = index;
while (left > 0 && nums[left - 1] == target){
left--;
}
right = index;
while (right < nums.length - 1 && nums[right + 1] == target) {
right++;
}
break;
}else if (target < nums[index]){
j = index - 1;
}else {
i = index + 1;
}
}
return new int[]{left,right};
}
總結:二分查詢,找到一個再擴散左右
33. 搜尋旋轉排序陣列
https://leetcode.cn/problems/search-in-rotated-sorted-array/description/?envType=study-plan-v2&envId=top-100-liked
public int search(int[] nums, int target) {
int p = 0;
for (int i = 1; i < nums.length; i++) {
if (nums[i - 1] > nums[i]) {
p = i;
break;
}
}
int left = 0;
int right = p - 1;
if (target <= nums[nums.length - 1]){
left = p;
right = nums.length - 1;
}
while (left <= right){
int index = left + ((right - left) >> 1);
if (target == nums[index]){
return index;
}else if (target < nums[index]){
right = index - 1;
}else {
left = index + 1;
}
}
return -1;
}
總結:先找到這個旋轉點p,再看從左側二分查詢,還是從右側二分查詢
153. 尋找旋轉排序陣列中的最小值
https://leetcode.cn/problems/find-minimum-in-rotated-sorted-array/description/?envType=study-plan-v2&envId=top-100-liked
public int findMin(int[] nums) {
int left = 0;
int right = nums.length - 1;
while (left < right){
int index = left + ((right - left) >> 1);
if (nums[index] > nums[right]){
left = index + 1;
}else {
right = index;
}
}
return nums[left];
}
總結:其實就是兩個上升的序列,若index的值>right的值說明,min一定不在index以及index左側,若index的值<right的值,說明min有可能是index以及index左側,一定不是index右側