zoukankan      html  css  js  c++  java
  • [LintCode] Find Minimum in Rotated Sorted Array

    Suppose a sorted array 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.

    You may assume no duplicate exists in the array.

    Example

    Given [4, 5, 6, 7, 0, 1, 2] return 0

     1 public class Solution {
     2     /**
     3      * @param nums: a rotated sorted array
     4      * @return: the minimum number in the array
     5      */
     6     public int findMin(int[] nums) {
     7         return findMinHelper(nums, 0, nums.length - 1);
     8     }
     9     
    10     private int findMinHelper(int[] nums, int startIdx, int endIdx)
    11     {
    12         if(endIdx - startIdx <= 1)
    13         {
    14             return nums[startIdx] < nums[endIdx] ? nums[startIdx] : nums[endIdx];
    15         }
    16         
    17         int mid = startIdx + (endIdx - startIdx) / 2;
    18         //right half not sorted, min value must be in the right half
    19         //nums[mid] can't be the minimum 
    20         if(nums[mid] > nums[endIdx])
    21         {
    22             return findMinHelper(nums, mid + 1, endIdx);
    23         }
    24         //nums[mid] <= nums[endIdx]
    25         else
    26         {
    27             return findMinHelper(nums, startIdx, mid);
    28         }
    29     }
    30 }

    Related Problems

    Find Minimum in Rotated Sorted Array II

    Search in Rotated Sorted Array II

  • 相关阅读:
    "ping: unknown host www.baidu.com"问题解决方式
    hive分区表中表字段操作
    hive常用函数
    spark书籍视频推荐
    pandas筛选排序
    pandas常用函数
    hive字符串函数
    Centos镜像下载
    记录操作 子查询 三表联查
    .net Excel转换DataSet
  • 原文地址:https://www.cnblogs.com/lz87/p/7494191.html
Copyright © 2011-2022 走看看