1、704
(1)题目描述
(2)代码实现
package com.hh.practice.leetcode.array.demo_02;
public class BinarySearch_704 {
public int search(int[] nums, int target) {
int i= 0,j = nums.length -1;
while (i <= j){
int mid = (i+j) >>> 1;
if (target < nums[mid]){
j = mid - 1;
} else if (nums[mid] < target) {
i = mid + 1;
}else {
return mid;
}
}
return -1;
}
//方式一
// public int search(int[] nums, int target) {
// for(int i = 0; i < nums.length; i++){
// if(target == nums[i]){
// return i;
// }
// }
// return -1;
// }
}
2、35
(1)题目描述
(2)代码实现
package com.hh.practice.leetcode.array.demo_02;
public class BinarySearch_35 {
//方式二
public static int searchInsert(int[] arr, int key) {
int i = 0;
int j = arr.length - 1;
while (i <= j) {
int mid = (i + j) >>> 1;
if (key <= arr[mid]) {
j = mid - 1;
} else{
i = mid + 1;
}
}
return i;
}
//方式一
// public int searchInsert(int[] nums, int target) {
// int low = 0;
// int high = nums.length - 1;
//
// while (low <= high) {
// int mid = (low + high) >>> 1;
// int midVal = nums[mid];
//
// if (midVal < target)
// low = mid + 1;
// else if (midVal > target)
// high = mid - 1;
// else
// return mid; // target found
// }
// //没找到就返回插入点,
// return low; // target not found.
// }
}
3、34
(1)题目描述‘
(2)代码实现
package com.hh.practice.leetcode.array.demo_02;
public class BinarySearch_34 {
public int[] searchRange(int[] nums, int target) {
int[] arr = new int[2];
arr[0] = binaryLeft(nums,target);
if (arr[0] == -1){
arr[1] = -1;
} else {
arr[1] = binaryRight(nums, target);
}
return arr;
}
/*
返回最靠左的元素索引
*/
public int binaryLeft(int[] arr, int key) {
int i = 0;
int j = arr.length - 1;
int candidate = -1;
while (i <= j) {
int mid = (i + j) >>> 1;
if (key < arr[mid]) {
j = mid - 1;
} else if (key > arr[mid]) {
i = mid + 1;
} else {
candidate = mid;
j = mid -1;
}
}
return candidate;
}
/*
返回最靠右的元素索引
*/
public int binaryRight(int[] arr, int key) {
int i = 0;
int j = arr.length - 1;
int candidate = -1;
while (i <= j) {
int mid = (i + j) >>> 1;
if (key < arr[mid]) {
j = mid - 1;
} else if (key > arr[mid]) {
i = mid + 1;
} else {
candidate = mid;
i = mid +1;
}
}
return candidate;
}
}
本文为学习笔记,所参考文章均已附上链接,若有疑问请私信!
创作不易,如果对你有点帮助的话麻烦点个赞支持一下!
新手小白,欢迎留言指正!