LeetCode 33.Search in Rotated Sorted Array(M)

题目:

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.

思路:

1.当数组长度为0时,return -1;

2.当数组长度为1时,比较nums[0]与target关系;

3.当数组长度大于1,且为rotated sorted array时,根据nums[mid]与nums[start]关系判断如何移动;

4.当数组长度大于1,但不是rotated sorted array时,用传统二分法;

5.注意,不仅仅要比较target与nums[mid]关系,还要比较其与nums[start]和nums[end]关系,否则会出现死循环。

代码:

 1 public class Solution {
 2     public int search(int[] nums, int target) {
 3         int start = 0,end = nums.length-1,mid = 0;
 4         if(nums.length == 0){
 5             return -1;
 6         }
 7         if(nums.length == 1){
 8             if(nums[0] == target){
 9                 return 0;
10             }else{
11                 return -1;
12             }
13         }
14         while(nums[start] > nums[end] && start + 1 < end){
15             mid = start + (end - start)/2;
16             if(nums[mid] == target){
17                 return mid;
18             }else if(nums[mid] > nums[start]){
19                 if(nums[mid] <= target ){
20                     start = mid;
21                 }else if(nums[start] <= target){
22                     end = mid;
23                 }else if(nums[start] >= target){
24                     start = mid;
25                 }
26             }else if(nums[mid] < nums[start]){
27                 if(nums[mid] >= target){
28                     end = mid;
29                 }else if(nums[start] <= target){
30                     end = mid;
31                 }else if(nums[start] >= target){
32                     start = mid;
33                 }
34             }
35         }
36         while(nums[start] < nums[end] && start + 1 < end){
37             mid = start + (end - start)/2;
38             if(nums[mid] == target){
39                 return mid;
40             }else if(nums[mid] >= target){
41                 end = mid;
42             }else{
43                 start = mid;
44             }
45         }
46         if(nums[start] == target){
47             return start;
48         }else if(nums[end] == target){
49             return end;
50         }
51         return -1;
52     }
53 }

 

posted @ 2017-03-31 16:28  程序媛家  阅读(187)  评论(0编辑  收藏  举报