• 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了。

  • 相关阅读:
    eclipse 提交代码至自己的github上
    今天是国庆
    我要完蛋了!!!
    C/C++知识点
    [c++]const增强
    [c++]指针作为函数参数传递的问题
    day3_JavaScript
    day2_HTML&CSS
    2017年度总结
    小游戏
  • 原文地址:https://www.cnblogs.com/openqt/p/4033553.html
Copyright © 2020-2023  润新知