zoukankan      html  css  js  c++  java
  • LeetCode 154.Find Minimum in Rotated Sorted Array II(H)(P)

    题目:

    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).

    Find the minimum element.

    The array may contain duplicates.

    思路:

    1.题目中指出sorted array,find target使用二分法。

    2.分为以下三种情况

    (1)数组只有一个元素:nums[0]即为最小值。

    (2)数组不是rotated sorted array,退化为sorted array:nums[0]即为最小值。

    (3)数组是rotated sorted array:nums[start] >= nums[end]:

    a:nums[mid]比左右数都小,返回nums[mid];

    b:nums[mid]大于nums[start].

    c:nums[mid]小于nums[end].

    d:nums[mid]等于nums[end],如下图,无法判断是start移到mid还是end移到mid,故start++;

    代码:

    public class Solution {
        public int findMin(int[] nums) {
            int start = 0,end = nums.length-1,mid=0;
    //length equals 1;
    if(nums.length == 1){ return nums[0]; }
    //is rotated sorted array;
    while(nums[start] >= nums[end] && start + 1 < end){ mid = start + (end - start)/2; if(nums[mid] < nums[mid+1] && nums[mid] < nums[mid-1]){ return nums[mid]; }else if(nums[mid] > nums[start]){ start = mid; }else if(nums[mid] < nums[start]){ end = mid; }else{ start++; } }
    //is not a rotated sorted array;
    if(nums[start] < nums[end]){ return nums[start]; } return nums[end]; } }
  • 相关阅读:
    BZOJ2061 : Country
    BZOJ3591: 最长上升子序列
    BZOJ4356 : Ceoi2014 Wall
    BZOJ2159 : Crash 的文明世界
    BZOJ2149 : 拆迁队
    BZOJ2739 : 最远点
    BZOJ4068 : [Ctsc2015]app
    BZOJ4361 : isn
    BZOJ4404 : [Neerc2015]Binary vs Decimal
    BZOJ4402 : Claris的剑
  • 原文地址:https://www.cnblogs.com/melbourne1102/p/6646684.html
Copyright © 2011-2022 走看看