Link: https://oj.leetcode.com/problems/search-in-rotated-sorted-array/
Time: O(logn), Space: O(1)
My code:
public class Solution {
public int search(int[] A, int target) {
if(A == null || A.length == 0) return -1;
return helper(A, target, 0, A.length);
}
public int helper(int[] A, int target, int l, int r){
while(l < r){
int m = (l+r)/2;
if(A[m] == target) return m;
else if(A[l] < A[m]){
if(A[l] < target && target < A[m]){
r = m - 1;
}
else{
l = m + 1;
}
}
else if(A[l] >= A[m]){
if(target > A[m] && target < A[l]){
l = m + 1;
}
else{
r = m - 1;
}
}
}
return l+1;
}
}
注意:上面的code几个等号都不对:
- l<=r
- A[l] <=A[m]
- A[l] <= target && target < A[m]
- target > A[m] && target <=A[r]
public class Solution {
public int search(int[] A, int target) {
if(A == null || A.length == 0) return -1;
return helper(A, target, 0, A.length-1);
}
public int helper(int[] A, int target, int l, int r){
while(l <= r){
int m = (l+r)/2;
if(A[m] == target) return m;
else if(A[l] <= A[m]){//left half is ordered 左边要包含等号
if(A[l] <= target && target < A[m])//注意这边的等号 左边要包含等号
r = m - 1;
}
else{
l = m + 1;
}
}
else {//A[l] > A[m], right half is ordered
if(target > A[m] && target <= A[r]){//左边要包含等号
l = m + 1;
}
else{
r = m - 1;
}
}
}
return -1;
}
}
2016.1
这段代码有问题。虽然 nums[low] <=target<nums[mid] 时,找左边;nums[mid]<target<=nums[high] 时,找右边是对的。但是 并不是target<nums[mid]的里层else满足就应该找右边;也不是target>nums[mid]的里层else满足就应该找左边。
e.g. 4, 5, 6, 7, 8, 1, 2, 3
l->nums[0]=4, h->nums[6]=3, mid>nums[3]= 7. If target = 8:
We have target > nums[mid], but target<=nums[high]不满足:进入else 的里层else,找左边,这是错误的。
当target>nums[mid] && target>nums[high]时,找右边或左边都有可能,要看nums[mid]和nums[high]的关系。
public class Solution {
public int search(int[] nums, int target) {
int low = 0;
int high = nums.length-1;
while(low <= high) {
int mid = low + (high-low)/2;
if(target == nums[mid]) return mid;
else if (target < nums[mid]) {
if(target >= nums[low]){
high = mid - 1;
}
else {
low = mid + 1;
}
}
else {//target > nums[mid]
if(target <= nums[high]) {
low = mid + 1;
}
else {
high = mid - 1;
}
}
}
return -1;
}
}