二分查找
35.搜索插入位置
思考:二分查找+先判定边界条件
记录:不需要二刷
class Solution {
public int searchInsert(int[] nums, int target) {
int left = 0,right = nums.length-1;
if(nums[right] < target){
return right+1;
}
if(nums[left] > target){
return 0;
}
while(left < right){
int middle = (left + right) / 2;
if(nums[middle] < target){
left++;
}else if(nums[middle] > target){
right--;
}else{
return middle;
}
}
return left;
}
}
74.搜索二维矩阵
思考:找到二维的二分查找规则,右上角往左是递减,往下是递增
记录:不需要二刷
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int i = 0,j = matrix[0].length-1;
while(i <= matrix.length-1 && j >= 0){
if(matrix[i][j] < target){
i++;
}else if(matrix[i][j] > target){
j--;
}else{
return true;
}
}
return false;
}
}
34.在排序数组中查找元素的第一个和最后一个位置
思考:二分查找+找边界
记录:不需要二刷
class Solution {
public int[] searchRange(int[] nums, int target) {
int left = 0,right = 0;
while(right < nums.length){
if(nums[left] == target){
while(right < nums.length && nums[right] == target){
right++;
}
return new int[]{left,right-1};
}else if(nums[left] < target){
left++;
right++;
}else{
return new int[]{-1,-1};
}
}
return new int[]{-1,-1};
}
}
33.搜索旋转排序数组
思考:如果用哈希,直接秒。如果按照题目初始想法,
- mid在【断崖】左侧,则nums[left] <= target < nums[mid],可以收缩左边界
- mid在【断崖】右侧,则nums[mid] < target <= nums[right],可以收缩右边界
记录:不需要二刷
class Solution {
public int search(int[] nums, int target) {
HashMap<Integer,Integer> hm = new HashMap<>();
for(int i = 0;i < nums.length;i++){
hm.put(nums[i],i);
}
if(hm.containsKey(target)){
return hm.get(target);
}
return -1;
}
}
153.搜索旋转排序数组中的最小值
思考:如果用内置api,直接秒
记录:不需要二刷
class Solution {
public int findMin(int[] nums) {
Arrays.sort(nums);
return nums[0];
}
}
4.寻找两个正序数组的中位数
思考:用一个大数组存这两个数组,然后return中间元素,注意可能会有小数所以除以2.0
记录:需要二刷
class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int[] nums = new int[nums1.length + nums2.length];
int p1 = 0,p2 = 0;
for(int i = 0;i < nums.length;i++){
if(p1 >= nums1.length){
nums[i] = nums2[p2];
p2++;
continue;
}
if(p2 >= nums2.length){
nums[i] = nums1[p1];
p1++;
continue;
}
if(nums1[p1] <= nums2[p2]){
nums[i] = nums1[p1];
p1++;
}else{
nums[i] = nums2[p2];
p2++;
}
}
if(nums.length % 2 != 0){
return nums[nums.length / 2];
}else{
return (nums[nums.length/2-1] + nums[nums.length/2]) / 2.0;
}
}
}