【题目】

说了一堆就是在旋转后的顺序数组中找最小值,时间复杂度必须是 O(log n) 

Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,2,4,5,6,7] might become:

  • [4,5,6,7,0,1,2] if it was rotated 4 times.
  • [0,1,2,4,5,6,7] if it was rotated 7 times.

Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]].

Given the sorted rotated array nums of unique elements, return the minimum element of this array.

You must write an algorithm that runs in O(log n) time.

 

Example 1:

Input: nums = [3,4,5,1,2]
Output: 1
Explanation: The original array was [1,2,3,4,5] rotated 3 times.

Example 2:

Input: nums = [4,5,6,7,0,1,2]
Output: 0
Explanation: The original array was [0,1,2,4,5,6,7] and it was rotated 4 times.

Example 3:

Input: nums = [11,13,15,17]
Output: 11
Explanation: The original array was [11,13,15,17] and it was rotated 4 times. 

 

【思路】

  • 因顺序排列,直接遍历找前<后的异常节点即可(复杂度不满足!!)
  • 为了logn,用二分法找。用mid来排除区间

【代码】

最直白不考虑复杂度的解法……

class Solution {
    public int findMin(int[] nums) {
        if(nums.length<=1)
            return nums[0];
        for(int i=1;i<nums.length;i++){
            if(nums[i]<nums[i-1])
                return nums[i];
        }
        return nums[0]; 
    }
}

 

二分logn 注意边界情况

class Solution {
    public int findMin(int[] nums) {
        int left=0;int right=nums.length-1;
        while(left<right){
            int mid=left+(right-left)/2;
            if(nums[mid]<nums[right])
                right=mid;
            if(nums[mid]>nums[right])
                left=mid+1;
        }
        return nums[left];
    }
}

 

 posted on 2021-08-19 14:17  alau  阅读(29)  评论(0编辑  收藏  举报