leetcode刷题记录 2018.7.13

1.有效的括号

给定一个只包括 '('')''{''}''['']' 的字符串,判断字符串是否有效。

有效字符串需满足:

  1. 左括号必须用相同类型的右括号闭合。
  2. 左括号必须以正确的顺序闭合。

注意空字符串可被认为是有效字符串。

示例 1:

输入: "()"
输出: true

示例 2:

输入: "()[]{}"
输出: true

示例 3:

输入: "(]"
输出: false

示例 4:

输入: "([)]"
输出: false

示例 5:

输入: "{[]}"
输出: true

分析:可以想到使用栈结构,遇到左括号进栈,遇到右括号时,判断栈是否为空以及该右括号是否和栈顶元素匹配,如果空栈or不匹配,return False,如果可以匹配,删除栈顶元素,继续执行for循环。最后判断栈是否为空,若空返回True,不空返回False。

代码:

class Solution:
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        dic = {'(':')','[':']','{':'}'}
        list1 = []
        for case in s:
            if case in dic.keys():
                list1.append(case)
            elif case in dic.values():
                if len(list1) == 0 or dic.get(list1[-1]) != case:
                    return False
                else:
                    list1.pop()
        if len(list1) == 0:
            return True
        else:
            return False

2.四数之和

给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c +d 的值与 target 相等?找出所有满足条件且不重复的四元组。

注意:

答案中不可以包含重复的四元组。

示例:

给定数组 nums = [1, 0, -1, 0, -2, 2],和 target = 0。

满足要求的四元组集合为:
[
  [-1,  0, 0, 1],
  [-2, -1, 1, 2],
  [-2,  0, 0, 2]
]
四数之和问题,最开始想利用itertools库,通过排列组合后计算,但是尝试了很多次,还是有问题。解答方法成功了两种,一下分别介绍一下。

法一:基本上参考了最接近的三数和的方法。

class Solution:
    def fourSum(self,nums, target):
        nums.sort()
        res = []
        for i in range(len(nums)):
            for j in range(i+1,len(nums)):
                if (j > i + 1 and nums[j] == nums[j - 1]) :
                    continue;
                left = j+1
                right = len(nums)-1
                while left < right:
                    sum1 = nums[i]+nums[j]+nums[left]+nums[right]
                    if sum1 < target:
                        left = left + 1
                    elif sum1 == target:
                        res.append([nums[i],nums[j],nums[left],nums[right]])
                        left = left + 1
                        right = right - 1
                    else:
                        right = right - 1
        cases = []                                        #会有重复的结果,干脆直接在后边删掉了
        for case in res:
            if case not in cases:
                cases.append(case)
        return cases

法二:哈希表,复杂度比法一要低。

class Solution:
    def fourSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        res, dicti = set(), {}
        numLen = len(nums)
        nums.sort()
        for i in range(numLen):
            for j in range(i+1, numLen):
                key = nums[i] + nums[j]
                if key not in dicti.keys():
                    dicti[key] = [(i,j)]
                else:
                    dicti[key].append((i,j))
        for i in range(numLen):
            for j in range(i+1, numLen-2):
                exp = target - nums[i] -nums[j]
                if exp in dicti.keys():
                    for tmpIndex in dicti[exp]:
                        if tmpIndex[0] > j:
                            res.add((nums[i], nums[j], nums[tmpIndex[0]], nums[tmpIndex[1]]))
        return [list(i) for i in res]

你可能感兴趣的:(leetcode)