Search in Rotated Sorted Array

  • leetcode 33
  • Hard
  • Company Tags: LinkedIn, Bloomberg, Uber, Facebook, Microsoft
  • Tags: Binary Search, Array
  • Similar Problems: Search in Rotated Sorted Array II, Find Minimun in Rotated Sorted Array
Description

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.

Previous Thinking
  • If the boundary is in a range, this range' s beginning should bigger than the tail;
  • To narrow the range, we can only get rid of the range without the boundary.
  • Use binary search.
C++ Solution
class Solution {
public:
    int search(vector<int>& nums, int target) {
        int first=0, last=nums.size() - 1;

        while(first <= last){
            int mid=first+(last-first)/2;
            if(nums[mid] == target){
                return mid;
            }

            if(nums[first] <= nums[mid]){
                if(nums[first] <= target && target < nums[mid])
                   last = mid - 1;
                else
                   first=mid + 1;
            }
            else{
                if(nums[mid] < target && target <= nums[last])
                   first = mid + 1;
                else
                   last = mid - 1;
            }
        }
        return -1;
    }
};
Java Solution
public class Solution {
    public int search(int[] nums, int target) {
        int first = 0, last = nums.length - 1;
        while(first != last){
            int mid = (first + last) / 2;
            if(nums[mid] == target) 
               return mid;

            if(nums[first] <= nums[mid]){
               if(nums[first] <= target && target < nums[mid])
                  last = mid - 1;
               else
                  first = mid + 1;
            }else{
                if(nums[mid] < target && target <= nums[last])
                   first = mid + 1;
                else
                   last = mid - 1;

            }

        }

            return -1;
    }
}
Post thinking

Binary Search Template

public int binarySearch(int[] nums, int target){
    int first = 0, last = nums.length - 1;
    while(first <= last){
        int mid = (first + last) / 2;
        if(nums[mid] = target) return target;

        if(nums[mid] < target){
            first = mid + 1;
        }else{
            last = mid - 1;
        }
   }
}

results matching ""

    No results matching ""