zoukankan      html  css  js  c++  java
  • LeetCode

    Find Minimum in Rotated Sorted Array II

    2015.1.23 11:41

    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.

    The array may contain duplicates.

    Solution:

      With duplicates in the array, it would be a little harder to perform binary search.

      Consider the ocassion "1 ... 1 ... 1", with the left, right and middle elements being all "1", you don't know if the rotated pivot will lie in the left or right half of the sequence. If we scan the sequence at one end, removing all duplicates that are equal to the other end, it will make a legal sequence for binary search.

      Here're some example data for my idea:

        {1, 1, -1, 0, 1, 1, 1} -> remove {1, 1} on the right -> {1, 1, -1, 0}

        {1, 1, 1, 2, 3} -> remove nothing -> {1, 1, 1, 2, 3}

        {1, 1, 1, 1, 1} -> all equal to the left end are removed -> {1}

      The next step would be a binary search, similar to the upper_bound() function in <algorithm>.

      Total time complexity is on average O(log(n)), but O(n) in worst cases. Space complexity is O(1).

    Accepted code:

     1 class Solution {
     2 public:
     3     int findMin(vector<int> &num) {
     4         int n = (int)num.size();
     5         
     6         while (n > 1 && num[0] == num[n - 1]) {
     7             --n;
     8         }
     9         
    10         if (n == 1 || num[0] < num[n - 1]) {
    11             return num[0];
    12         }
    13         
    14         int ll, mm, rr;
    15         
    16         ll = 0;
    17         rr = n - 1;
    18         while (rr - ll > 1) {
    19             mm = ll + (rr - ll) / 2;
    20             if (num[mm] >= num[ll]) {
    21                 ll = mm;
    22             } else {
    23                 rr = mm;
    24             }
    25         }
    26         
    27         return num[rr];
    28     }
    29 };
  • 相关阅读:
    Jquery DataTable初探
    小程序-组件component和模版template的选择和使用
    小程序-canvas在IOS手机层级最高无法展示问题
    小程序-二维码生成
    css深入理解之 border
    css那些事儿4 背景图像
    css那些事儿3 列表与浮动
    css那些事儿2 经典两列布局
    css那些事儿2 盒子模型
    css那些事儿1 css选择符与管理
  • 原文地址:https://www.cnblogs.com/zhuli19901106/p/4243849.html
Copyright © 2011-2022 走看看