码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode]

时间:2014-11-26 22:40:43      阅读:240      评论:0      收藏:0      [点我收藏+]

标签:leetcode   算法   

问题描述:

Follow up for "Find Minimum in Rotated Sorted Array":
What if duplicates are allowed?

Would this affect the run-time complexity? How and why?

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.


基本思想:

如果存在A[i] > A[i+1]的点,则A[i+1]一定是最小点。

如果不存在这样的点,则在遍历时记录一个min,返回最小的即可。

该方法最坏情况下时间复杂度是O(n),是最navie的方法。


代码:

    int findMin(vector<int> &num) {   //C++
        if(num.size() == 1)
            return num[0];

        int min = num[0];
        int i = 0;
        for(int i = 0; i < num.size()-1; i++)
        {
            if(num[i]>num[i+1])
                return num[i+1];
            if(min > num[i])
                min = num[i];
        }
        min = (min > num[num.size()-1])?num[num.size()-1]:min;
        return min;
        
    }

better method  O(lgn)

public int findMin(int[] A) {  //JAVA
   int L = 0, R = A.length - 1;
   while (L < R && A[L] >= A[R]) {
      int M = (L + R) / 2;
      if (A[M] > A[R]) {
         L = M + 1;
      } else if (A[M] < A[L]) {
         R = M;
      } else {   // A[L] == A[M] == A[R]
         L = L + 1;
      }
   }
   return A[L];
}



[leetcode]

标签:leetcode   算法   

原文地址:http://blog.csdn.net/chenlei0630/article/details/41522747

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!