1、LeetCode153. Find Minimum in Rotated Sorted Array
Description:
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.
Example 1:
Input: [3,4,5,1,2] Output: 1
Example 2:
Input: [4,5,6,7,0,1,2] Output: 0
代码:
class Solution {
public int findMin(int[] nums) {
int l = 0;
int h = nums.length - 1;
while (l < h){
int m = l + (h-l) / 2;
if (nums[m] <= nums[h]){
h = m;
} else {
l = m+1;
}
}
return nums[l];
}
}
2、LeetCode34. Find First and Last Position of Element in Sorted Array
Description:
Given an array of integers
nums
sorted in ascending order, find the starting and ending position of a giventarget
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]
.
Example 1:
Input: nums = [5,7,7,8,8,10], target = 8 Output: [3,4]
Example 2:
Input: nums = [5,7,7,8,8,10], target = 6 Output: [-1,-1]
代码:
class Solution {
public int[] searchRange(int[] nums, int target) {
int first = binarySearch(nums, target);
int last = binarySearch(nums, target + 1)-1;
if (first == nums.length || nums[first] != target){
return new int[]{-1,-1};
} else {
return new int[]{first,Math.max(first, last)};
}
}
private int binarySearch(int[] nums, int target){
int l = 0;
int h = nums.length;
while (l<h){
int mid = l + (h-l)/2;
if (nums[mid] >= target){
h = mid;
} else {
l = mid + 1;
}
}
return l;
}
}
3、LeetCode540. Single Element in a Sorted Array
Description:
Given a sorted array consisting of only integers where every element appears exactly twice except for one element which appears exactly once. Find this single element that appears only once.
Example 1:
Input: [1,1,2,3,3,4,4,8,8] Output: 2
Example 2:
Input: [3,3,7,7,10,11,11] Output: 10
分析:
假设 index 为 Single Element 在数组中的位置。在 index 之后,数组中原来存在的成对状态被改变。若 m 为偶数,且 m + 1 < index,则 nums[m] == nums[m + 1]。若m + 1 >= index,那么 nums[m] != nums[m + 1]。
从上面的规律看出,若 nums[m] == nums[m + 1],那么 index 所在的数组位置为 [m + 2, h],此时假设 l = m + 2;若 nums[m] != nums[m + 1],则 index 所在的数组位置为 [l, m],此时令 h = m。由于 h 的赋值表达式为 h = m,所以循环条件也就只能使用 l < h 这种形式。
代码:
class Solution {
public int singleNonDuplicate(int[] nums) {
if(null == nums || nums.length < 1){
return -1;
}
int l = 0;
int len = nums.length;
int h = len - 1;
while(l < h){
int mid = l + ((h-l)>>1);
if(mid % 2 == 1 ){
mid--;
}
if (nums[mid] == nums[mid+1]){
l = mid + 2;
} else {
h = mid;
}
}
return nums[l];
}
}