Binary Search Common Problems
find the first number index that is larger or equals to target.
(就是说返回target的最后一个index,或者比target大的第一个index,如果一定要确定放在target的最后一个index上,那最后一定要check right指针是不是对应target)
**//if we only have one element, and it's keeping >
int binarySearch(int[] arr, int target){
int left = 0, right = arr.length - 1;
while (left < right) {
int mid = left + (right - left) / 2;
if (arr[mid] < target) {
left = mid + 1;
}else{ //if arr[mid] >= target
right = mid;
}
}
return right;
}** //not sure if this code is right
int binarySearch(int[] arr, int target){
int left = 0, right = arr.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] < target) {
left = mid + 1;
}else{ //if arr[mid] >= target
right = mid - 1;
}
}
if (right == arr.length - 1) {
return -1;
}
return right + 1;
}
find the first index that is larger than target:
int binarySearch(int[] arr, int target){
int left = 0, right = arr.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] <= target) {
left = mid + 1;
}else{ //if arr[mid] > target
right = mid;
}
}
return right;
}
find the last index that is less or equals to target:
find the last index that is less than target:(?)
int binarySearch(int[] arr, int target){
int left = 0, right = arr.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] < target) {
left = mid + 1;
}else{ //if arr[mid] >= target
right = mid;
}
}
return right - 1;;
}
find the first index that is equals to target:
int binarySearch(int[] arr, int target){
int left = 0, right = arr.length - 1;
while (left < right) {
int mid = left + (right - left) / 2;
if (arr[mid] < target) {
left = mid + 1;
}else{ //if arr[mid] >= target
right = mid;
}
}
if (arr[left] == val) {
return left;
}
return -1;;
}
find the last index that equals to target:
int binarySearch(int[] arr, int target){
int left = 0, right = arr.length - 1;
while (left < right) {
int mid = left + (right - left) / 2;
if (arr[mid] <= target) {
left = mid;
}else{ //if arr[mid] >= target
right = mid - 1;;
}
}
if (arr[right] == val) {
return right;
}
return -1;;
}
find the index range of given target:
class Solution {
public int[] searchRange(int[] nums, int target) {
if(nums == null || nums.length == 0) return new int[]{-1,-1};
//int[] res = new int[];
int left = 0;
int right = nums.length - 1;
while(left <= right) {
int mid = (left + right) / 2;
if(nums[mid] == target) {
int i = mid;
int j = mid;
while(i >= 0 && nums[i] == target) {
i--;
}
while(j <= nums.length -1 && nums[j] == target) {
j++;
}
return new int[]{i+1, j-1};
}
if(nums[mid] > target) {
right = mid - 1;
}
if(nums[mid] < target) {
left = mid + 1;
}
}
return new int[]{-1,-1};
}
}

浙公网安备 33010602011771号