`
hcx2013
  • 浏览: 88793 次
社区版块
存档分类
最新评论

Search in Rotated Sorted Array

 
阅读更多

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.

 

public class Solution {
    public int search(int[] nums, int target) {
    	if (nums == null || nums.length == 0) {
    		return -1;
    	}
        int start = 0;
        int end = nums.length - 1;
        while (start <= end) {
        	int mid = (start + end) / 2;
        	if (target < nums[mid]) {
        		if (nums[mid] < nums[end]) {
        			end = mid - 1;
        		} else {
        			if (target < nums[start]) {
        				start = mid + 1;
        			} else {
        				end = mid - 1;
        			}
        		}
        	} else if (target > nums[mid]) {
        		if (nums[mid] > nums[start]) {
        			start = mid + 1;
        		} else {
        			if (target > nums[end]) {
        				end = mid - 1;
        			} else {
        				start = mid + 1;
        			}
        		}
        	} else {
        		return mid;
        	}
        }
        return -1;
    }
}

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics