LeetCode基本记录【3】// BASIC NOTES AND CODES OF LEETCODE [ 3 ]

LeetCode基本记录【3】

43. Multiply Strings

Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2.

Note:

The length of both num1 and num2 is < 110.
Both num1 and num2 contains only digits 0-9.
Both num1 and num2 does not contain any leading zero.
You must not use any built-in BigInteger library or convert the inputs to integer directly.
# 实际上就是模拟人在做笔算乘法时候的步骤,被乘数分别于乘数的各个位相乘,并将结果按照乘数的各个位所代表的倍数(10的幂次)错位相加
# 为了方便运算,直接每做完一次一位数乘多位数就和已得到的和错位相加
class Solution(object):
    def multiply(self, num1, num2):
        """
        :type num1: str
        :type num2: str
        :rtype: str
        """
        ret = ''
        res = [0] * (len(num1) + len(num2))
        for i in range(len(num1)):
            carry = 0
            for j in range(len(num2)):
                newcarry = (res[-i-1-j] + (int(num1[-i-1]) * int(num2[-j-1]) + carry)) // 10
                res[-i-1-j] = (res[-i-1-j] + (int(num1[-i-1]) * int(num2[-j-1]) + carry)) % 10 
                carry = newcarry
            res[-i-1-j-1] = carry
        head0 = True
        for k in res:
            if k != 0:
                head0 = False
            if not head0:
                ret = ret + (str(k))
        return ret if ret else '0'

46. Permutations

Given a collection of distinct numbers, return all possible permutations.

For example,
[1,2,3] have the following permutations:

[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]

# dfs, 递归回溯求解,这里没有限制条件,所以没有backtracking,直接把所有的都加进来即可
class Solution(object):
    def permute(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        res = []
        self.dfs(nums, [], res)
        return res

    def dfs(self, nums, path, res):
        if not nums:
            res.append(path)
            return
        for i in range(len(nums)):
            self.dfs(nums[:i] + nums[i+1:], path + [nums[i]], res)

47. Permutations II

Given a collection of numbers that might contain duplicates, return all possible unique permutations.

For example,
[1,1,2] have the following unique permutations:

[
[1,1,2],
[1,2,1],
[2,1,1]
]

# 注意,为了使得相同的数都是挨着的,也就是nums[i] == nums[i-1]的判断可以起作用,那么应该先对nums进行排序
class Solution(object):
    def permuteUnique(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        nums = sorted(nums)
        res = []
        path = []
        self.helper(nums, path, res)
        return res

    def helper(self, nums, path, res):
        if not nums:
            res.append(path)
            return
        for i in range(len(nums)):
            if i > 0 and nums[i] == nums[i-1]:
                continue
            self.helper(nums[:i] + nums[i+1:], path + [nums[i]], res)

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]
]

# 旋转可以分解成上下交换和对角线交换,也就是求转置,两个操作的叠加,意识到这个就不难写出。
class Solution(object):
    def rotate(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: void Do not return anything, modify matrix in-place instead.
        """

        for idx in range(len(matrix)//2):
            t = matrix[idx]
            matrix[idx] = matrix[-idx-1]
            matrix[-idx-1] = t        
        for i in range(len(matrix)):
            for j in range(i+1,len(matrix)):
                tmp = matrix[i][j]
                matrix[i][j] = matrix[j][i]
                matrix[j][i] = tmp

49. Group Anagrams

Given an array of strings, group anagrams together.

For example, given: [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”],
Return:

[
[“ate”, “eat”,”tea”],
[“nat”,”tan”],
[“bat”]
]

Note: All inputs will be in lower-case.

class Solution(object):
    def groupAnagrams(self, strs):
        """
        :type strs: List[str]
        :rtype: List[List[str]]
        """
        res = []
        ana = {}
        count = 0
        for st in strs:
            if not ana.has_key(''.join(sorted(st))):
                ana[''.join(sorted(st))] = count
                res.append([st])
                count += 1
            else:
                res[ana[''.join(sorted(st))]].append(st)
        return res

50. Pow(x, n)

Implement pow(x, n).

Example 1:

Input: 2.00000, 10
Output: 1024.00000

Example 2:

Input: 2.10000, 3
Output: 9.26100

# 考虑不能直接对x乘n次,而是要通过把底数逐渐增大指数逐渐减小的方法来做power,这样就是log(n)的次数。考虑特殊情况,如0和负数
class Solution(object):
    def myPow(self, x, n):
        """
        :type x: float
        :type n: int
        :rtype: float
        """
        if n == 0:
            return 1
        if n < 0:
            return 1 / self.myPow(x, -n)
        if n % 2 == 0:
            return self.myPow( x * x, n // 2)
        else:
            return x * self.myPow( x * x, n // 2)

54. Spiral Matrix

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

For example,
Given the following matrix:

[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]

You should return [1,2,3,6,9,8,7,4,5].

# 在discuss区发现的巧妙的解法,每次取出第一行,然后旋转剩下的,再取出第一行,如此重复即可
# 常规的话可能需要recursive,一圈一圈来做,下面的解法很巧妙。
class Solution(object):
    def spiralOrder(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: List[int]
        """
        path = []
        while matrix:
            path = path + list(matrix[0])
            if len(matrix) != 1:
                matrix = self.rotate(matrix[1:])
            else:
                break
        return path

    def rotate(self,mat):
        return zip(*mat)[::-1]

55. Jump Game

Given an array of non-negative integers, you are initially positioned at the first index of the array.

Each element in the array represents your maximum jump length at that position.

Determine if you are able to reach the last index.

For example:
A = [2,3,1,1,4], return true.

A = [3,2,1,0,4], return false.

# 维护一个m,表示已经遍历到当前位置的情况下,此前(包括本次)所有可能情况中最远所能到达的位置,如果一旦某个点是达不到的(i > m)
# 那么直接return,否则需要继续遍历,都遍历完成的话,说明可以到达最后一个位置。
class Solution(object):
    def canJump(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        m = 0
        for i in range(len(nums)):
            if i > m:
                return False
            m = max( i+nums[i], m )
        return True

56. Merge Intervals

Given a collection of intervals, merge all overlapping intervals.

For example,
Given [1,3],[2,6],[8,10],[15,18],
return [1,6],[8,10],[15,18].

# 注意sorted函数可以指定按照某种方式或者某个成员排序,用法是在参数key=指定一个lambda表达式
# 另外,list的append方法直接修改list,无需赋值,否则会将list修改成append方法的返回值也就是NoneType

# Definition for an interval.
# class Interval(object):
#     def __init__(self, s=0, e=0):
#         self.start = s
#         self.end = e

class Solution(object):
    def merge(self, intervals):
        """
        :type intervals: List[Interval]
        :rtype: List[Interval]
        """

        ret = []
        for itm in sorted(intervals, key = lambda itm : itm.start):
            if ret and itm.start <= ret[-1].end:
                ret[-1].end = max(itm.end, ret[-1].end)
            else:
                ret.append(itm)
        return ret

59. Spiral Matrix II

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

For example,
Given n = 3,
You should return the following matrix:

[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]

# 每次都旋转然后加上去,另,get了一种转置矩阵的小方法:zip(*mat),zip可以将各个参数的每个对应的位置进行组合zip,形成tuple
# 我们用*加在mat前面,相当于将每一行作为一个参数,zip后就是每一列组成的tuple组成的list,然后map(list,zip(*mat))一下即可。
# 旋转和转置就差了一个翻转过程,根据clockwise还是counterclockwise进行判断。
class Solution(object):
    def generateMatrix(self, n):
        """
        :type n: int
        :rtype: List[List[int]]
        """
        if not n :
            return []
        ret = [[n * n]]
        l = n*n
        while l - len(ret) > 0 :
            l, h = l - len(ret), l
            ret = [range(l, h)] + self.rot(ret)
        return ret

    def rot(self, mat):
        return map(list, zip(*mat[::-1]))

又十道题了。。。进度还需要加快。。。。

2018年03月30日01:41:38

posted @ 2018-03-30 01:43  毛利小九郎  阅读(101)  评论(0编辑  收藏  举报