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,4 +1,7 @@
package com.nbee.solution.practice; package com.nbee.solution.practice;
import java.util.Arrays;
class BinarySearch { class BinarySearch {
public static int binarySearchBasic(int[] nums, int target) { public static int binarySearchBasic(int[] nums, int target) {
int i = 0, j = nums.length - 1;//设置指针和初始值 int i = 0, j = nums.length - 1;//设置指针和初始值
@ -7,11 +10,9 @@ class BinarySearch {
int m = (i + j) >>> 1; //按位右移补零操作符。相当于除2解决溢出问题 int m = (i + j) >>> 1; //按位右移补零操作符。相当于除2解决溢出问题
if (target < nums[m]) {//如果中间值大于目标值,则将右指针向左移动 if (target < nums[m]) {//如果中间值大于目标值,则将右指针向左移动
j = m - 1; j = m - 1;
} } else if (nums[m] < target) {//如果中间值小于目标值,则将左指针向右移动
else if (nums[m] < target){//如果中间值小于目标值,则将左指针向右移动
i = m + 1; i = m + 1;
} } else {
else {
return m; return m;
} }
} }
@ -30,14 +31,63 @@ class BinarySearch {
int m = (i + j) >>> 1; int m = (i + j) >>> 1;
if (target < nums[m]) { if (target < nums[m]) {
j = m; j = m;
} } else if (nums[m] < target) {
else if (nums[m] < target){
i = m + 1; i = m + 1;
} } else {
else {
return m; return m;
} }
} }
return -1; 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;
}
} }