1128XF

二分查找

class Solution {
public static void main(String[] args) {
// System.out.println(new Solution().find132pattern(new int[]{7, 6, 5, 1, 2, 4, 3}));
int[] arr = {1, 2, 2, 2, 2, 3, 3, 4,5,5,5};
System.out.println(new Solution().left_bound(arr, 1));
System.out.println(new Solution().left_bound2(arr, 1));
System.out.println(new Solution().right_bound(arr, 1));
System.out.println(new Solution().right_bound2(arr, 1));
System.out.println(new Solution().binarySearch(arr, 1));
}

int left_bound(int[] nums, int target) {
if (nums.length == 0) {
return -1;
}
int left = 0;
int right = nums.length; // 注意

while (left < right) { // 注意
int mid = (left + right) / 2;
if (nums[mid] == target) {
right = mid;
} else if (nums[mid] < target) {
left = mid + 1;
} else if (nums[mid] > target) {
right = mid; // 注意
}
}
return left;
}
int left_bound2(int[] nums, int target) {
if (nums.length == 0) {
return -1;
}
int left = 0;
int right = nums.length-1; // 注意

while (left <= right) { // 注意
int mid = (left + right) / 2;
if (nums[mid] == target) {
right = mid-1;
} else if (nums[mid] < target) {
left = mid + 1;
} else if (nums[mid] > target) {
right = mid-1; // 注意
}
}
return left;
}

int right_bound(int[] nums, int target) {
if (nums.length == 0) {
return -1;
}
int left = 0, right = nums.length;

while (left < right) {
int mid = (left + right) / 2;
if (nums[mid] == target) {
left = mid + 1; // 注意
} else if (nums[mid] < target) {
left = mid + 1;
} else if (nums[mid] > target) {
right = mid;
}
}
return left - 1; // 注意
}
int right_bound2(int[] nums, int target) {
if (nums.length == 0) {
return -1;
}
int left = 0, right = nums.length-1;

while (left <= right) {
int mid = (left + right) / 2;
if (nums[mid] == target) {
left = mid+1; // 注意
} else if (nums[mid] < target) {
left = mid+1;
} else if (nums[mid] > target) {
right = mid-1;
}
}
return left-1; // 注意
}

int binarySearch(int[] nums, int target) {
int left = 0;
int right = nums.length - 1; // 注意

while (left <= right) { // 注意
int mid = (right + left) / 2;
if (nums[mid] == target) {
return mid;
} else if (nums[mid] < target) {
left = mid + 1; // 注意
} else if (nums[mid] > target) {
right = mid - 1; // 注意
}
}
return -1;
}
}
参考:https://www.zhihu.com/question/36132386/answer/712269942

posted on 2021-03-31 10:31  1128XF  阅读(59)  评论(0编辑  收藏  举报

导航