Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e.,
0 1 2 4 5 6 7
might become4 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了。