𝑰’𝒎 𝒉𝒉𝒈, 𝑰 𝒂𝒎 𝒂 𝒈𝒓𝒂𝒅𝒖𝒂𝒕𝒆 𝒔𝒕𝒖𝒅𝒆𝒏𝒕 𝒇𝒓𝒐𝒎 𝑵𝒂𝒏𝒋𝒊𝒏𝒈, 𝑪𝒉𝒊𝒏𝒂.
- 🏫 𝑺𝒉𝒄𝒐𝒐𝒍: 𝑯𝒐𝒉𝒂𝒊 𝑼𝒏𝒊𝒗𝒆𝒓𝒔𝒊𝒕𝒚
- 🌱 𝑳𝒆𝒂𝒓𝒏𝒊𝒏𝒈: 𝑰’𝒎 𝒄𝒖𝒓𝒓𝒆𝒏𝒕𝒍𝒚 𝒍𝒆𝒂𝒓𝒏𝒊𝒏𝒈 𝒅𝒆𝒔𝒊𝒈𝒏 𝒑𝒂𝒕𝒕𝒆𝒓𝒏, 𝑳𝒆𝒆𝒕𝒄𝒐𝒅𝒆, 𝒅𝒊𝒔𝒕𝒓𝒊𝒃𝒖𝒕𝒆𝒅 𝒔𝒚𝒔𝒕𝒆𝒎, 𝒎𝒊𝒅𝒅𝒍𝒆𝒘𝒂𝒓𝒆 𝒂𝒏𝒅 𝒔𝒐 𝒐𝒏.
- 💓 𝑯𝒐𝒘 𝒕𝒐 𝒓𝒆𝒂𝒄𝒉 𝒎𝒆:𝑽𝑿
- 📚 𝑴𝒚 𝒃𝒍𝒐𝒈: 𝒉𝒕𝒕𝒑𝒔://𝒉𝒉𝒈𝒚𝒚𝒅𝒔.𝒃𝒍𝒐𝒈.𝒄𝒔𝒅𝒏.𝒏𝒆𝒕/
- 💼 𝑷𝒓𝒐𝒇𝒆𝒔𝒔𝒊𝒐𝒏𝒂𝒍 𝒔𝒌𝒊𝒍𝒍𝒔:𝒎𝒚 𝒅𝒓𝒆𝒂𝒎
题目
看官方
解法
看完官方解答,你一脸懵逼,我花了一些时间才找到最好的办法,首先,先写出最初始的代码,就是最原始的二分查找
public int searchInsert(int[] nums, int target) {
int n = nums.length;
int pos = n;
int low = 0;
int high = n - 1;
while (low <= high) {
int mid = low + ((high - low) >> 1);
if (nums[mid] > target) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return pos;
}
这个大家都会写,那么在哪里确定= 又在哪里确定位置?pos = mid; ,教你一个办法。无非四种情况:
- 找到第一个== target值的位置
- 找到第一个> target值的位置,这里是严格大于
- 找到最后一个==target的数
- 找到最后一个< target的数字
他们基础代码都一样,就是等号在哪取,位置在哪选有区别,最好的办法就是写个例子,再想一下就知道了,比如找到第一个== target值的位置,命中目标了,左边还有数字啊,所以要继续往左找,代码就该这样写:
if (nums[mid] >= target) {
pos = mid;
high = mid - 1;
} else {
low = mid + 1;
}
剩下的同理:这里我给出代码,与其绕来绕去,不如自己写简单的例子,比划一下就知道了。
package com.company.xx.array.T34在排序数组中查找元素的第一个和最后一个位置;
import java.util.ArrayList;
public class Solution {
public int searchInsert(int[] nums, int target) {
int n = nums.length;
int pos = n;
int low = 0;
int high = n - 1;
while (low <= high) {
int mid = low + ((high - low) >> 1);
if (nums[mid] >= target) {
pos = mid;
high = mid - 1;
} else {
low = mid + 1;
}
}
return pos;
}
public int searchInsert2(int[] nums, int target) {
int n = nums.length;
int pos = n;
int low = 0;
int high = n - 1;
while (low <= high) {
int mid = low + ((high - low) >> 1);
if (nums[mid] > target) {
pos = mid;
high = mid - 1;
} else {
low = mid + 1;
}
}
return pos;
}
public int searchInsert3(int[] nums, int target) {
int n = nums.length;
int pos = n;
int low = 0;
int high = n - 1;
while (low <= high) {
int mid = low + ((high - low) >> 1);
if (nums[mid] > target) {
high = mid - 1;
} else {
pos = mid;
low = mid + 1;
}
}
return pos;
}
public int searchInsert4(int[] nums, int target) {
int n = nums.length;
int pos = n;
int low = 0;
int high = n - 1;
while (low <= high) {
int mid = low + ((high - low) >> 1);
if (nums[mid] >= target) {
high = mid - 1;
} else {
pos = mid;
low = mid + 1;
}
}
return pos;
}
public int[] searchRange(int[] nums, int target) {
int left = searchInsert(nums, target);
int right = searchInsert3(nums, target);
if (left == right) {
return new int[]{-1, -1};
}
return new int[]{left, right-1};
}
public static void main(String[] args) {
int[] nums = {1, 2, 3, 5};
System.out.println(new Solution().searchInsert3(nums, 4));
}
}
知道了这些,就可以解除这道题了,我们只需要找到第一个和target相等的,再找到第一个>target的就可以了,这是nums[]有target的情况,如果nums[]里面没有的话,left和right就都是指向第一个>target的元素了。也就是left==right。
|