704. 二分查找
思路:有序数组,无重复元素,升序->二分法
public int search(int[] nums, int target) {
int left_index = 0;
int right_index = nums.length - 1;
while (left_index <= right_index) {
int mid_index = (left_index + right_index) / 2;
if (nums[mid_index] == target)
return mid_index;
else if (nums[mid_index] > target)
right_index = mid_index - 1;
else
left_index = mid_index + 1;
}
return -1;
}
35. 搜索插入位置
思路:排序数组;无重复元素 的 升序 ->二分法
public int searchInsert(int[] nums, int target) {
int left = 0;
int right = nums.length-1;
while (left <= right) {
int mid = (left + right) / 2;
if (nums[mid] == target)
return mid;
else if (nums[mid] > target)
right = mid - 1;
else
left = mid + 1;
}
return right + 1;
}
34. 在排序数组中查找元素的第一个和最后一个位置
错误思路:错以为target如果存在,只会出现两次。升序数组->二分法;返回值->长度为2的int[];
更正:二分法,当找到第一个target时,分别继续往左以及往右查找target得到startingIndex和EndingIndex
public int[] searchRange(int[] nums, int target) {
int[] res = new int[2];
res[0] = findStartingIndex(nums,target);
res[1] = findEndingIndex(nums,target);
return res;
}
public int findStartingIndex(int[] nums, int target){
int index= -1;
int left = 0;
int right = nums.length -1;
while(left <= right){
int midpoint = left + (right - left)/2;
if(nums[midpoint] >=target){
right = midpoint -1;
}else{
left = midpoint+1;
}
if(nums[midpoint] ==target)
index = midpoint;
}
return index;
}
public int findEndingIndex(int[] nums, int target){
int index= -1;
int left = 0;
int right = nums.length -1;
while(left <= right){
int midpoint = left + (right - left)/2;
if(nums[midpoint] <= target){
left = midpoint+1;
}else{
right = midpoint -1;
}
if(nums[midpoint] ==target)
index = midpoint;
}
return index;
}