128. Longest Consecutive Sequence
这道题Python用dictionary, Java用Hashmap做。首先将数组中所有元素作为dictionary的key(value为True)放到dictionary里面,然后在遍历dictionary中的键值对,对每次遍历,向左右移动,如果左或右键存在dictionary中,则连续序列的长度加一。要将遍历过的值设为false
class Solution(object):
def longestConsecutive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# construct a dict for element in the array
if len(nums) < 1:
return 0
hashMap = { }
for i in nums:
hashMap[i] = True
maxV = 0
for k,v in hashMap.items():
if not v:
continue
left = k - 1
right = k + 1
while hashMap.has_key(left) and hashMap[left]:
hashMap[left] = False
left -= 1
while hashMap.has_key(right) and hashMap[right]:
hashMap[right] = False
right += 1
n = right - left - 1
if n > maxV:
maxV = n
return maxV
152. Maximum Product Subarray
用动态规划来解决,维持当前最大值的时候也要维持当前最小值,因为当前最小值可能在乘以个负数以后翻身成为最大值。。。参考:
http://blog.csdn.net/chilseasai/article/details/47344323
class Solution(object):
def maxProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) < 1:
return 0;
if len(nums) == 1:
return nums[0]
maxCur = nums[0]
minCur = nums[0]
maxAll = nums[0]
for i in range(1, len(nums)):
temp = maxCur
maxCur = max(max(nums[i] * maxCur, nums[i]), nums[i] * minCur)
minCur = min(min(nums[i] * minCur, nums[i]), nums[i] * temp)
maxAll = max(maxAll, maxCur)
return maxAll