Search in Rotated Sorted Array
Problem
Suppose a sorted array 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
).
You are given a target value to search. If found in the array return its index, otherwise return -1
.
You may assume no duplicate exists in the array.
Example
For [4, 5, 1, 2, 3]
and target=1
, return 2
.
For [4, 5, 1, 2, 3]
and target=0
, return -1
.
Challenge
O(logN) time
Note
找中点:若起点小于中点,说明左半段没有旋转,否则说明右半段没有旋转。
在左右半段分别进行二分法的操作。
Solution
public class Solution {
public int search(int[] A, int target) {
int start = 0, end = A.length-1, mid = 0;
while (start <= end) {
mid = (start+end)/2;
if (A[mid] == target) return mid;
if (A[start] <= A[mid]) {
if (A[start] <= target && target <= A[mid]) end = mid-1;
else start = mid+1;
}
else {
if (A[mid] < target && target <= A[end]) start = mid+1;
else end = mid-1;
}
}
return -1;
}
}
Search in Rotated Sorted Array II
Problem
Follow up for "Search in Rotated Sorted Array":
What if duplicates are allowed?
Would this affect the run-time complexity? How and why?
Write a function to determine if a given target is in the array.
Note
只判断有无,就容易了。
Solution
还是用二分法优化
public class Solution {
public boolean search(int[] nums, int target) {
if (nums == null || nums.length == 0) return false;
int start = 0, end = nums.length-1;
while (start <= end) {
int mid = start+(end-start)/2;
if (nums[mid] == target || nums[start] == target || nums[end] == target) return true;
if (nums[start] < nums[mid]) {
if (nums[start] <= target && target < nums[mid]) end = mid-1;
else start = mid+1;
}
else if (nums[start] > nums[mid]) {
if (nums[mid] < target && target <= nums[end]) start = mid+1;
else end = mid-1;
}
else {
if (nums[start] != target) start++;
if (nums[end] != target) end--;
}
}
return false;
}
}
Updated 2018-08
class Solution {
public boolean search(int[] nums, int target) {
int start = 0, mid = 0, end = nums.length-1;
while (start <= end) {
mid = start+(end-start)/2;
if (nums[mid] == target || nums[start] == target || nums[end] == target) return true;
if (nums[start] < nums[mid]) {
if (nums[start] < target && target < nums[mid]) end = mid-1;
else start = mid+1;
} else if (nums[start] > nums[mid]) {
if (nums[mid] < target && target < nums[end]) start = mid+1;
else end = mid-1;
} else {
start++;
end--;
}
}
return false;
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。