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.

Have you met this question in a real interview? Yes
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

Tags 
Sorted Array Array LinkedIn Binary Search Uber Facebook
Related Problems 
Medium Search in Rotated Sorted Array II 40 %
Easy Search a 2D Matrix

有序数组的题, 二分法, 根据mid的位置再确定start 和end的位置, 画图分情况

  三种情况

The idea is that when rotating the array, there must be one half of the array that is still in sorted order.
For example, 6 7 1 2 3 4 5, the order is disrupted from the point between 7 and 1. So when doing binary search, we can make a judgement that which part is ordered and whether the target is in that range, if yes, continue the search in that half, if not continue in the other half.

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

  

  

 

posted @ 2017-07-31 11:35  apanda009  阅读(173)  评论(0编辑  收藏  举报