[leetCode刷题笔记]2017.02.19
来源:互联网 发布:android 全景拼接算法 编辑:程序博客网 时间:2024/06/03 23:49
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
- [leetCode刷题笔记]2017.02.19
- Leetcode刷题笔记
- LeetCode刷题笔记
- LeetCode刷题笔记
- leetcode刷题笔记
- [leetCode刷题笔记]2017.02.01
- [leetCode刷题笔记]2017.02.02
- [leetCode刷题笔记]2017.02.03
- [leetCode刷题笔记]2017.02.04
- [leetCode刷题笔记]2017.02.05
- [leetCode刷题笔记]2017.02.06
- [leetCode刷题笔记]2017.02.07
- [leetCode刷题笔记]2017.02.08
- [leetCode刷题笔记]2017.02.09
- [leetCode刷题笔记]2017.02.11
- [leetCode刷题笔记]2017.02.12
- [leetCode刷题笔记]2017.02.13
- [leetCode刷题笔记]2017.02.14
- linux perf - 性能测试和优化工具
- 常见前端面试题及答案(下)
- 今天听到一首好歌“沉默是金”
- 让Kubernetes集群使用本地image registry
- STL容器之deque双向队列
- [leetCode刷题笔记]2017.02.19
- 内网穿透(NAT穿透)之ngrok搭建服务器
- 文章标题
- 1086.Tree Traversals Again (25)...to be continued...
- IPC-Message-queue示例
- Spark Streaming中的操作函数分析
- Android面试题之Progress控件通过10秒的时间完成进度显示
- 机器学习中的特征工程
- 36:Copy List with Random Pointer