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

  • 相关阅读:
    数据的增、删、改(jQuery.Ajax)
    tomcat内置jdk(tomcat集成jdk)(windows环境)
    进行数据库进程的杀死
    矩阵与自然基向量
    实对称矩阵
    坐标变换
    设置PySpark的Python版本
    CentOS7中安装Python3.6
    一个矩阵有几个实特征向量
    centos7系统设置固定IP
  • 原文地址:https://www.cnblogs.com/lz87/p/7494191.html
Copyright © 2011-2022 走看看