[leetCode刷题笔记]2017.02.19

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
            

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值