BinarySearch[4]153. Find Minimum in Rotated Sorted Array

1.Simple Easy Thinking Solution

Binary Search

  • Time Complexity: O(logn)
class Solution {
    public int findMin(int[] nums) {
    // The difference between 33. Search in Rotated Sorted Array and this one is:
        // This question find the mim and the other is to find the target.
        
        int start = 0, end = nums.length -1;
        while(start +1 <end){
            int mid = start + (end - start)/2;
            if(nums[mid] > nums[start]){
                if(nums[mid] < nums[end] && nums[mid-1] < nums[mid]) end = mid;
                else start = mid;
            }
            else if(nums[mid] < nums[start]){
                if(nums[mid] > nums[end] && nums[mid-1] > nums[mid]) start = mid;
                else end = mid;
            }
        }
        
        if(nums[start] > nums[end]) return nums[end];
        return nums[start];
    }
}

2.Improved Binary Search Solution2

  • Time Complexity: O(logn)

Analysis: In the rotated array,like x+3,x+4,x+5,x(min),x+1,x+2;
In ths array, we have the conclusion that if start < end, the array is in rotate.

  1. start > end if this array is rotated, so we can find mim value in this scope;
    if start <end, it means that the start is the min.
  2. how to verify the first asmuption:
    I use the array[x+3,x+4,x(min),x+1,x+2]:
    we can see that, the smaller will always in the right, the numbers in the left will always more than the right numbers.
class Solution {
    public int findMin(int[] nums) {
        /*Thinking:
        1. end < start ==> rotated ;
        2. array: x+2,x+3,x(min),x+1;
        */
        int start = 0, end = nums.length -1;
                
        while(start + 1 < end){
            int mid = start + (end - start)/2;
            if(nums[mid] < nums[end]){
                end = mid;
            }
            else{
                start = mid;
            }
        }
        
        if(nums[end] < nums[start]) return nums[end];
        return nums[start];
    }
}

3. Divide and Conquer分治法

  • Time Complexity: O(logn)

Recursive
Thoughts: Every time, separate the array into two parts, find the min in the two parts, compare the two min and find the minmize number.

class Solution {
    public int findMin(int[] nums) {
        return Fmin(nums, 0, nums.length-1);
    }
    
    private int Fmin(int[] nums, int start, int end){
        if(start == end || start +1 == end) return Math.min(nums[start],nums[end]);
        
        if(nums[start] < nums[end]) return nums[start];
        
        int mid = start + (end - start)/2;
        return Math.min(Fmin(nums, mid, end), Fmin(nums, start, mid));
    }
}
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页