Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
Input: [1,3,5,6], 5
Output: 2
Input: [1,3,5,6], 2
Output: 1
Input: [1,3,5,6], 7
Output: 4
Input: [1,3,5,6], 0
Output: 0
class Solution {
public int searchInsert(int[] nums, int target) {
int start = 0, end = nums.length - 1, mid;
while(start <= end){
mid = (start + end) >> 1;
if(nums[mid] == target){
return mid;
}
else if(nums[mid] > target){
end = mid - 1;
}
else{
start = mid + 1;
}
}
return start;
}
}
Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.
Your algorithm‘s runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1].
Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]
Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]
class Solution {
public int[] searchRange(int[] nums, int target) {
int[] res = new int[2];
if(nums.length == 0){
res[0] = res[1] = -1;
return res;
}
res[0] = find(nums, target, true);
res[1] = find(nums, target, false);
if(res[0] >= nums.length || nums[res[0]] != target){
res[0] = -1;
res[1] = -1;
}
return res;
}
int find(int[] nums, int target, boolean left){
int mid;
int start = 0, end = nums.length - 1;
while(start <= end){
mid = (start + end) >> 1;
if(nums[mid] > target){
end = mid - 1;
}
else if(nums[mid] == target){
if(left){
end = mid - 1;
}
else{
start = mid + 1;
}
}
else{
start = mid + 1;
}
}
return left ? start : end;
}
}
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
Find the minimum element.
You may assume no duplicate exists in the array.
Input: [3,4,5,1,2]
Output: 1
Input: [4,5,6,7,0,1,2]
Output: 0
class Solution {
public int findMin(int[] nums) {
int n = nums.length, start = 0, end = n - 1, mid;
while(start < end){
if(nums[start] < nums[end]){
return nums[start];
}
mid = (start + end) >> 1;
if(nums[mid] >= nums[start]){
start = mid + 1;
}
else{
end = mid;
}
}
return nums[start];
}
}
原文:https://www.cnblogs.com/echie/p/9592186.html