class Solution: # @param num, a list of integer # @return an integer def findMin(self, num): n=len(num) strt=0 nd=n-1 while num[strt]>num[nd]: mid=(strt+nd)//2 if num[strt]>num[mid]: nd=mid elif num[strt]<num[mid]: strt=mid else: return num[nd] return num[strt]
Wednesday, October 22, 2014
Leetcode: Find Minimum in Rotated Sorted Array @Python
Pay attention to the ending condition and edge cases.
Leetcode: Find Minimum in Rotated Sorted Array II @Python
class Solution: # @param num, a list of integer # @return an integer def findMin(self, num): n=len(num) strt=0 nd=n-1 while nd-strt>1: mid=(strt+nd)//2 if num[strt]<num[nd]: return num[strt] elif num[strt]>num[nd]: if num[strt]>num[mid]: nd=mid else: strt=mid else: strt+=1 return num[strt] if num[strt]<num[nd] else num[nd]
Wednesday, October 8, 2014
Leetcode: Maximum Product Subarray @Python
Dynamic Programming, O(n) time complexity and O(1) space complexity.
Scan the list once,keep updating two variables mincrt and maxcrt.
mincrt is the minimum product end with the last element scanned. maxcrt is the maximum counterpart.
rst is used to store the maximal product so far.
Every time when updating with the new element, mincrt and maxcrt are from either the product with the new element ,or breaking up multiplication and starting from the new element.
Scan the list once,keep updating two variables mincrt and maxcrt.
mincrt is the minimum product end with the last element scanned. maxcrt is the maximum counterpart.
rst is used to store the maximal product so far.
Every time when updating with the new element, mincrt and maxcrt are from either the product with the new element ,or breaking up multiplication and starting from the new element.
class Solution: # @param A, a list of integers # @return an integer def maxProduct(self, A): mincrt=maxcrt=rst=A[0] for i in range(1,len(A)): mincrt,maxcrt=min(A[i],A[i]*mincrt,A[i]*maxcrt),max(A[i],A[i]*mincrt,A[i]*maxcrt) rst=max(rst,maxcrt) return rst
Subscribe to:
Posts
(
Atom
)