Leetcode 33 Search in Rotated Sorted Array

HowieLee59發表於2018-10-30

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

這個題目的意思是在一個逆轉的陣列中進行二分查詢,使用的方法為虛擬節點(類似於一致性雜湊中的虛擬節點),將虛擬節點對映到真實節點即可。

1)虛擬節點法

class Solution {
    public int search(int[] nums, int target) {
        int n = nums.length;
        int low = 0 , high = n - 1;
        while(low < high){//設定虛擬節點
            int mid = (low + high) / 2;
            if(nums[mid] > nums[high]){
                low = mid + 1;
            }else{
                high = mid;
            }
        }
        int rot = low;
        low = 0;
        high = n - 1;
        while(low <= high){
            int mid = (low + high) / 2;
            int real = (mid + rot) % n;//虛擬節點對映到真實的節點。
            if(nums[real] == target){
                return real;
            }else if(nums[real] < target){
                low = mid + 1;
            }else{
                high = mid - 1;
            }
        }
        return -1;
    }
}

2)

class Solution {
    public int search(int[] nums, int target) {
        int l=0;
        int h=nums.length-1;
        while(l<=h){
            int mid=(l+h)/2;
            int midValue=(nums[mid]<nums[0])==(target<nums[0])?nums[mid]:target<nums[0]?Integer.MIN_VALUE:Integer.MAX_VALUE;
            if(target==midValue){
                return mid;
            }else if(target>midValue){
                l=mid+1;
            }else{
                h=mid-1;
            }
        }
        return -1;
    }
}

 

相關文章