Update BinarySearch.java

master
wangsiyuan 2024-07-10 16:58:37 +08:00
parent 35e5acb50f
commit 022850f76c
1 changed files with 67 additions and 17 deletions

View File

@ -1,17 +1,18 @@
package com.nbee.solution.practice;
import java.util.Arrays;
class BinarySearch {
public static int binarySearchBasic(int[] nums, int target){
int i = 0 ,j = nums.length - 1;//设置指针和初始值
while (i <= j){//此处的条件是i<=j而不是i<j
public static int binarySearchBasic(int[] nums, int target) {
int i = 0, j = nums.length - 1;//设置指针和初始值
while (i <= j) {//此处的条件是i<=j而不是i<j
// int m = ((i + j) / 2);
int m = (i + j) >>> 1; //按位右移补零操作符。相当于除2解决溢出问题
if (target < nums[m]){//如果中间值大于目标值,则将右指针向左移动
j = m - 1;
}
else if (nums[m] < target){//如果中间值小于目标值,则将左指针向右移动
if (target < nums[m]) {//如果中间值大于目标值,则将右指针向左移动
j = m - 1;
} else if (nums[m] < target) {//如果中间值小于目标值,则将左指针向右移动
i = m + 1;
}
else {
} else {
return m;
}
}
@ -24,20 +25,69 @@ class BinarySearch {
}
public static int binarySearchAlternative(int[] nums, int target){
int i = 0 ,j = nums.length;
while (i < j){
public static int binarySearchAlternative(int[] nums, int target) {
int i = 0, j = nums.length;
while (i < j) {
int m = (i + j) >>> 1;
if (target < nums[m]){
if (target < nums[m]) {
j = m;
}
else if (nums[m] < target){
} else if (nums[m] < target) {
i = m + 1;
}
else {
} else {
return m;
}
}
return -1;
}
public static int binarySearch01(int[] nums, int target) {
int i = 0, j = nums.length;
while (1 < j - i) {
int m = (i + j) >>> 1;
if (target < nums[m]) {
j = m;
} else {
i = m;
}
}
if (nums[i] == target) {
return i;
} else {
return -1;
}
}
public static int binarySearchLeftMost(int[] nums, int target) {
int i = 0, j = nums.length - 1;
int candidate = -1;
while (i <= j) {
int m = (i + j) >>> 1;
if (target < nums[m]) {
j = m - 1;
} else if (nums[m] < target) {
i = m + 1;
} else {
candidate = m;
j = m - 1;
}
}
return candidate;
}
public static int binarySearchRightMost(int[] nums, int target) {
int i = 0, j = nums.length - 1;
int candidate = -1;
while (i <= j) {
int m = (i + j) >>> 1;
if (target < nums[m]) {
j = m - 1;
} else if (nums[m] < target) {
i = m + 1;
} else {
candidate = m;
i = m + 1;
}
}
return candidate;
}
}