LeetCode 33. Search in Rotated Sorted Array

原题链接在这里:https://leetcode.com/problems/search-in-rotated-sorted-array/

题目:

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.

Your algorithm's runtime complexity must be in the order of O(log n).

Example 1:

Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4

Example 2:

Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1

题解:

因为rotate, 所以不能直接用Binary Search, 需要进行 二次判定.

通过nums[l] < nums[mid]判断左侧是正常升序,没有rotation, 若是这种情况下 target >= nums[l] && target <= nums[mid] 就在左侧查找,其他情况右侧查找.

否则右侧正常升序,没有rotation, 若是这种情况下target >= nums[mid] && target <= nums[r] 就在右侧查找,其他情况左侧查找.

Time Complexity: O(logn). n = nums.lengthj.

Space: O(1).

AC Java:

 1 class Solution {
 2     public int search(int[] nums, int target) {
 3         if(nums == null || nums.length == 0){
 4             return -1;
 5         }
 6         
 7         int l = 0; 
 8         int r = nums.length - 1; 
 9         while(l <= r){
10             int mid = l + (r - l) / 2; 
11             if(nums[mid] == target){
12                 return mid;
13             }
14             
15             if(nums[mid] < nums[r]){
16                 if(target >= nums[mid] && target <= nums[r]){
17                     l = mid + 1;
18                 }else{
19                     r = mid - 1;
20                 }
21             }else{
22                 if(target >= nums[l] && target <= nums[mid]){
23                     r = mid - 1;
24                 }else{
25                     l = mid + 1;
26                 }
27             }
28         }
29         
30         return -1;
31     }
32 }

类似Find Minimum in Rotated Sorted Array

跟上Search in Rotated Sorted Array II.

原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/4855301.html