leetcode practice - python3 (2)

21. Merge Two Sorted Lists

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

思路比较简单,先找l1, l2的head较小的做head,然后遍历两个表,把小的接到末尾,最后把剩下的接到末尾:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        if l1 == None:
            return l2
        if l2 == None:
            return l1

        head = None
        if l1.val < l2.val:
            head = l1
            l1 = l1.next
        else:
            head = l2
            l2 = l2.next
        tail = head

        while l1 != None and l2 != None:
            if l1.val < l2.val:
                tail.next = l1
                tail = l1
                l1 = l1.next
            else:
                tail.next = l2
                tail = l2
                l2 = l2.next

        if l1 != None:
            tail.next = l1
        elif l2 != None:
            tail.next = l2

        return head

Beat 99.95% python3 at 2018-04-27

22. Generate Parentheses

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, given n = 3, a solution set is:
[
“((()))”,
“(()())”,
“(())()”,
“()(())”,
“()()()”
]

思路:给定n,将会生成长度为2n的串,其中 “(” 跟 “)” 数量相等。使用dfs的方式,维护剩余 “(” 跟 “)” 的数量,剩余的右括号数必需不少于左括号数

class Solution:
    def generate(self, results, current, left, right):
        if left == 0 and right == 0:
            results.append(current)
        elif right >= left:
            if left > 0:
                self.generate(results, current + "(", left - 1, right)
            if right > 0:
                self.generate(results, current + ")", left, right - 1)

    def generateParenthesis(self, n):
        """
        :type n: int
        :rtype: List[str]
        """
        results = []
        self.generate(results, "", n, n)
        return results

Beat 97.85% python3 at 2018-05-01

class Solution:
    def generate(self, results, current, left, right):
        if left == 0 and right == 0:
            results.append(current)
            return

        if left > 0:
            self.generate(results, current + "(", left - 1, right)
        if right > left:
            self.generate(results, current + ")", left, right - 1)

    def generateParenthesis(self, n):
        """
        :type n: int
        :rtype: List[str]
        """
        results = []
        self.generate(results, "", n, n)
        return results

Beat 97.85% python3 at 2018-05-01,这两个基本相同

class Solution:
    def generateParenthesis(self, n):
        results = []
        def generate(current, left, right):
            if left == 0 and right == 0:
                results.append(current)
                return

            if left > 0:
                generate(current + "(", left - 1, right)
            if right > left:
                generate(current + ")", left, right - 1)

        generate('', n, n)
        return results

Beat 100.0% python3 at 2018-05-01

39. Combination Sum

Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.
The same repeated number may be chosen from candidates unlimited number of times.

Note:
All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.

Example 1:
Input: candidates = [2,3,6,7], target = 7,
A solution set is:
[
[7],
[2,2,3]
]

Example 2:
Input: candidates = [2,3,5], target = 8,
A solution set is:
[
[2,2,2,2],
[2,3,3],
[3,5]
]

思路:DFS

class Solution:
    def combinationSum(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        results = []
        def solve(begin, current, tar):
            if tar == 0:
                ans = copy.deepcopy(current)
                results.append(ans)
                return

            for i in range(begin, len(candidates)):
                c = candidates[i]
                if c <= tar:
                    current.append(c)
                    solve(i, current, tar-c)
                    current.pop()

        cur = []
        solve(0, cur, target)
        return results

Beat 81.95% python3 at 2018-05-02

class Solution:
    def combinationSum(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        results = []
        def solve(begin, current, tar):
            if tar == 0:
                results.append(current)
                return

            for i in range(begin, len(candidates)):
                c = candidates[i]
                if c <= tar:
                    solve(i, current + [c], tar-c)

        cur = []
        solve(0, cur, target)
        return results

Beat 99.57% python3 at 2018-05-02

48. Rotate Image

You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).

Note:
You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.

Example 1:
Given input matrix =
[
[1,2,3],
[4,5,6],
[7,8,9]
],

rotate the input matrix in-place such that it becomes:
[
[7,4,1],
[8,5,2],
[9,6,3]
]

Example 2:
Given input matrix =
[
[ 5, 1, 9,11],
[ 2, 4, 8,10],
[13, 3, 6, 7],
[15,14,12,16]
],
rotate the input matrix in-place such that it becomes:
[
[15,13, 2, 5],
[14, 3, 4, 1],
[12, 6, 8, 9],
[16, 7,10,11]
]

思路:
[
[1,2,3],
[4,5,6],
[7,8,9]
],
先上下对称:
[
[7,8,9],
[4,5,6],
[1,2,3],
],
再对角交换:
[
[7,4,1],
[8,5,2],
[9,6,3]
]

class Solution:
    def rotate(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: void Do not return anything, modify matrix in-place instead.
        """
        n = len(matrix)
        if n <= 1:
            return

        # swap row
        for i in range(n // 2):
            matrix[i], matrix[n-i-1] = matrix[n-i-1], matrix[i]

        for i in range(n):
            for j in range(i):
                matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]

Beat 96.54% python3 at 2018-05-04

49. Group Anagrams

Given an array of strings, group anagrams together.

Example:
Input: [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”],
Output:
[
[“ate”,”eat”,”tea”],
[“nat”,”tan”],
[“bat”]
]

Note:
All inputs will be in lowercase.
The order of your output does not matter.

思路:用字典,给字符串排序,以排好序的串做key查字典,找到则加到value集合里,找不到,加入字典。

class Solution:
    def groupAnagrams(self, strs):
        """
        :type strs: List[str]
        :rtype: List[List[str]]
        """
        dict = {}
        for s in strs:
            ss = "".join(sorted(s))
            if ss in dict:
                dict[ss].append(s)
            else:
                dict[ss] = [s]

        ans = []
        for key, l in dict.items():
            ans.append(l)

        return ans

Beat 99.88% python3 at 2018-05-09

猜你喜欢

转载自blog.csdn.net/guzhou_diaoke/article/details/80327785