Leetcode 33. Search in Rotated Sorted Array

来源:互联网 发布:管理车间 软件系统 编辑:程序博客网 时间:2024/05/01 23:54

Leetcode 33. Search in Rotated Sorted Array

question:

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.

Analysis:
This question is for binary search, but because there is not totally same with binary search.

Use the nums[mid]  nums[end] to judge the order in the 2nd part of the array. to judge where is the first element should be in a array before rotating, then we can get two condition that the target is imposible in the sorted part, and other than these two conditions, the target must be in the sorted part.

for example when we use, It means that second half is sorted, then we need to judge if target is less than nums[mid] or target is larger than nums[end], the target will be impossible in the second half of the array.

if(nums[mid] < nums[end]){

public class Solution {    public int search(int[] nums, int target) {      int length = nums.length;      if(length == 0)        return -1;      return help(nums, target, 0, length - 1);    }        public int help(int[] nums, int target, int start, int end){      if(start > end)        return -1;      if(start == end)      {         if(nums[start] == target)            return start;          return -1;      }      int mid = (start + end) / 2;      if(nums[mid] == target)        return mid;      //the logic      // else if(nums[mid] < nums[end] && target > nums[mid])      //   return help(nums, target, start + 1, end);      //The first element before rotating is before the mid position      if(nums[mid] < nums[end]){         if(target < nums[mid])            return help(nums, target, start, mid - 1);         else if(target > nums[end])            return help(nums, target, start, mid - 1);          else            return help(nums, target, mid + 1, end);      }      // the first element before rotating is exactely or after the mid position      if(nums[mid] > nums[end]){         if(target > nums[mid])            return help(nums, target, mid + 1, end);         else if(target < nums[start])            return help(nums, target, mid + 1, end);          else            return help(nums, target, start , mid - 1);      }      return - 1;    }}


0 0
原创粉丝点击