zoukankan      html  css  js  c++  java
  • 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.

    分析:

    排好序的数组基于某个位置截断然后前后两段交换一下,

    [0,1,2], [4,5,6,7] => [4,5,6,7], [0,1,2]

     

    前后两段都应该是递增序列,所以遍历列表,如果某个元素小于前一个,那就是截断的第一段序列的开始,就是要找的整个列表里面的最小值。

     

    class Solution:
    
        # @param num, a list of integer
        # @return an integer
        def findMin(self, num):
            pre = num[0]
            for i in num[1:]:
                if i < pre:
                    return i
                else:
                    pre = i
            return num[0]
    
    if __name__ == '__main__':
        s = Solution()
        assert s.findMin([4, 5, 6, 7, 0, 1, 2]) == 0
        print 'PASS'

    结:

    这个问题从直觉上就是这个解法,直接写了代码就Accepted了。

  • 相关阅读:
    google
    学习Linux第六天
    对比教学大纲
    周 记
    《世界是数字的》读后感
    《我是一只IT小小鸟》读后感
    前端小知识
    JavaScript 执行机制
    执行栈和任务队列
    支付宝前端员工培训手册
  • 原文地址:https://www.cnblogs.com/openqt/p/4033553.html
Copyright © 2011-2022 走看看