[leetCode刷题笔记]2017.02.22

来源:互联网 发布:单片机中断响应过程 编辑:程序博客网 时间:2024/06/16 09:57

209. Minimum Size Subarray Sum

这道题用两个指针做。。。end先跑,跑到sum>s或者数组末尾。然后start开始跑(跑的条件是sum >= s and start <= end)跑完后如果length还是原始值则返回0,否则返回最小subarray长度


class Solution(object):    def minSubArrayLen(self, s, nums):        """        :type s: int        :type nums: List[int]        :rtype: int        """        # sub-array length        length = len(nums) + 1        sum = 0        # two point        start = 0        end = 0                while (end < len(nums) and start < len(nums)):            # end run first            while (sum < s and end < len(nums)):                sum += nums[end]                end += 1            # start run            while (sum >= s and start <= end):                length = min(length, end - start)                sum -= nums[start]                start += 1                # when cannot get sub array larger than sum        if length == len(nums) + 1:            return 0        else:            return length            


216. Combination Sum III

这道题还是用递归做。。用python比Java简单太多了。。。

class Solution(object):    def combinationSum3(self, k, n):        """        :type k: int        :type n: int        :rtype: List[List[int]]        """                        output = []        # count is number of element in nums        # sum sum of values        # start value is 1 to 9                def search(start, count, sum, nums):            if count > k or sum > n:                return            if count == k and sum == n:                output.append(nums)                return            for i in range(start + 1, 10):                search(i, count + 1, sum + i, nums+[i])                        search(0, 0, 0, [])                return output

219. Contains Duplicate II

用dict做,很简单

class Solution(object):    def containsNearbyDuplicate(self, nums, k):        """        :type nums: List[int]        :type k: int        :rtype: bool        """                nums_dict = {}                for i in range(len(nums)):            if nums[i] in nums_dict:                j = nums_dict[nums[i]]                if i - j <= k:                    return True            nums_dict[nums[i]] = i        return False


0 0
原创粉丝点击