您的位置:首页 > 其它

Leetcode 33 Search in Rotated Sorted Array

2017-06-05 12:07 351 查看
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
).

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.

search 啊。。log是个好东西

所以为啥不想到binary search??

脑子还不够啊

原始版

public class Solution {
public int search(int[] nums, int target) {
if(nums == null || nums.length == 0){
return -1;
}

if(nums[0] >= target){
for(int i = 0; i < nums.length; i++){
if(nums[i] == target){
return i;
}
}
return -1;
}else if(nums[0] < target){
for(int i = nums.length - 1; i >= 0; i--){
if(nums[i] == target){
return i;
}
}
return -1;
}
return -1;
}
}

binary 版本

public class Solution {
public int search(int[] A, int target) {
int lo = 0;
int hi = A.length - 1;
while (lo < hi) {
int mid = (lo + hi) / 2;
if (A[mid] == target) return mid;

if (A[lo] <= A[mid]) {
if (target >= A[lo] && target < A[mid]) {
hi = mid - 1;
} else {
lo = mid + 1;
}
} else {
if (target > A[mid] && target <= A[hi]) {
lo = mid + 1;
} else {
hi = mid - 1;
}
}
}
return A[lo] == target ? lo : -1;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: