LintCode刷题笔记

1. Depth-first Search(DFS)

1.1 Palindrome Partitioning

题目跳转:https://www.lintcode.com/problem/palindrome-partitioning/description

在这里插入图片描述
在这里插入图片描述
因为每个path都要包含所有的字符,即第一个起点必在0,所以不用在backTracking的外层循环start。

图取自题解

class Solution:
    """
    @param: s: A string
    @return: A list of lists of string
    """
    def partition(self, s):
        # write your code here
        # 2020/7/7
        def isPlindrome(s, start, end):
            while start < end:  # start == end不用判断
                if s[start] != s[end]:
                    return False
                start += 1
                end -= 1
            return True
            
        def backTracking(s, start, path, res):
            if start >= len(s):
                res.append(path.copy())
                return
            for end in range(start, len(s)):
                if not isPlindrome(s, start, end):
                    continue
                path.append(s[start: end + 1])
                backTracking(s, end + 1, path, res)
                path.pop()
        
        res = []
        path = []
        backTracking(s, 0, path, res)
        return res

1.2 Split String

题目跳转:https://www.lintcode.com/problem/split-string/description

在这里插入图片描述
在这里插入图片描述
每个start走一步或者两步,在此基础上再更新下一个start,也是走一步或者两步。后面都走完了就pop pop pop回来。

class Solution:
    """
    @param: : a string to be split
    @return: all possible split string array
    """

    def splitString(self, s):
        # write your code here
        # 2020/7/6
        def mysplit(s, res, curr, start):
            if start == len(s):
                res.append(curr.copy())
                return
            chars = [1, 2]
            for c in chars:
                if start + c <= len(s):
                    curr.append(s[start: start + c])
                    mysplit(s, res, curr, start + c)
                    curr.pop()
            
        res = []
        curr = []
        mysplit(s, res, curr, 0)
        return res

1.3 Combination Sum II

题目跳转:https://www.lintcode.com/problem/combination-sum-ii/description

在这里插入图片描述

在这里插入图片描述
图自题解

num排序之后,每个递归阶段(start相同为一个递归阶段),都只用重复数的第一个数来算,后面紧接的数如果和本递归阶段前一个数相同,就会导致组合重复,所以直接continue。

class Solution:
    """
    @param num: Given the candidate numbers
    @param target: Given the target number
    @return: All the combinations that sum to target
    """
    def combinationSum2(self, num, target):
        # write your code here
        # 2020/7/8
        def dfs(num, start, curr, res, residue):
            if not residue:
                res.append(curr.copy())
                return
            for i in range(start, len(num)):
                if num[i] > residue:
                    return
                if i > start and num[i] == num[i - 1]:
                    continue
                curr.append(num[i])
                dfs(num, i + 1, curr, res, residue - num[i])
                curr.pop()
        
        num.sort()
        curr = []
        res = []
        dfs(num, 0, curr, res, target)
        return res

1.4 Combination Sum

题目跳转:https://www.lintcode.com/problem/combination-sum/description

在这里插入图片描述

相比于Combination Sum II,循环里dfs传入i而非 i + 1,是因为元素允许重复使用,但要先用list+set+sortcandidates预处理。

class Solution:
    """
    @param candidates: A list of integers
    @param target: An integer
    @return: A list of lists of integers
    """
    def combinationSum(self, candidates, target):
        # write your code here
        # 2020/7/8
        def dfs(s, start, residue, curr, res):
            if residue < 0: return
            if residue == 0:
                res.append(curr.copy())
                return
            for i in range(start, len(s)):
                curr.append(s[i])
                dfs(s, i, residue - s[i], curr, res)
                curr.pop()
                
        candidates = list(set(candidates))
        candidates.sort()
        curr = []
        res = []
        dfs(candidates, 0, target, curr, res)
        return res

1.5 Combinations

题目跳转:https://www.lintcode.com/problem/combinations/description

在这里插入图片描述
n不变,residue用来计数,每个迭代阶段就是选的第几个数(residue相同),循环 i 来遍历剩余的数,并且i + 1 是下一个迭代阶段的起始。

class Solution:
    """
    @param n: Given the range of numbers
    @param k: Given the numbers of combinations
    @return: All the combinations of k numbers out of 1..n
    """
    def combine(self, n, k):
        # write your code here
        # 2020/7/8
        def dfs(start, n, residue, curr, res):
            if residue < 1:
                res.append(curr.copy())
                return
            for i in range(start, n + 1):
                curr.append(i)
                dfs(i + 1, n, residue - 1, curr, res)
                curr.pop()
        
        curr = []
        res = []
        dfs(1, n, k, curr, res)
        return res

1.6 Subsets II

题目跳转:https://www.lintcode.com/problem/subsets-ii/description

在这里插入图片描述
在这里插入图片描述

观察题目,结果的长度覆盖了从0len(nums),所以用外层的循环用来宏观控制长度,每个循环进去只取这个长度的结果:

range(len(nums) + 1)

在每个迭代阶段内去重(前提是已排序):

if i > start and nums[i] == nums[i - 1]:
	continue
class Solution:
    """
    @param nums: A set of numbers.
    @return: A list of lists. All valid subsets.
    """
    def subsetsWithDup(self, nums):
        # write your code here
        # 2020/7/8
        def dfs(nums, start, residue, curr, res):
            
            if not residue:
                res.append(curr.copy())
                return
            for i in range(start, len(nums)):
                if i > start and nums[i] == nums[i - 1]:
                    continue
                curr.append(nums[i])
                dfs(nums, i + 1, residue - 1, curr, res)
                curr.pop()
        
        nums.sort()
        curr = []
        res = []
        for residue in range(len(nums) + 1):
            dfs(nums, 0, residue, curr, res)
        return res

1.7 Subsets

题目跳转:https://www.lintcode.com/problem/subsets/description

Subsets II 类似,只是提供的nums元素并不重复。
在这里插入图片描述

在这里插入图片描述

因此只需把去重的部分去掉即可。

class Solution:
    """
    @param nums: A set of numbers
    @return: A list of lists
    """
    def subsets(self, nums):
        # write your code here
        # 2020/7/8
        def dfs(nums, start, residue, curr, res):
            if residue <= 0:
                res.append(curr.copy())
                return
            for i in range(start, len(nums)):
                curr.append(nums[i])
                dfs(nums, i + 1, residue - 1, curr, res)
                curr.pop()
        
        nums.sort()
        curr = []
        res = []
        for i in range(len(nums) + 1):
            dfs(nums, 0, i, curr, res)
        return res

1.8 Letter Combinations of a Phone Number

题目跳转:https://www.lintcode.com/problem/letter-combinations-of-a-phone-number/description

在这里插入图片描述
在这里插入图片描述
residue代表还剩几个数字没被覆盖。用来显式让结果覆盖每个数字,也是控制每次dfs的终止。
不能用if start > len(digits): return来控制终止,因为它最终一定会大于len(digits),导致res里会有长度小于digits的结果。所以它的作用就是为了深入每个迭代阶段,并限制它循环的起始。

range(start, len(digits))
class Solution:
    """
    @param digits: A digital string
    @return: all posible letter combinations
    """
    def letterCombinations(self, digits):
        # write your code here
        # 2020/7/9
        relation = {
            "2": ["a", "b", "c"],
            "3": ["d", "e", "f"],
            "4": ["g", "h", "i"],
            "5": ["j", "k", "l"],
            "6": ["m", "n", "o"],
            "7": ["p", "q", "r", "s"],
            "8": ["t", "u", "v"],
            "9": ["w", "x", "y", "z"]
        }
        
        def dfs(digits, start, residue, relation, curr, res):
            if residue <= 0 and len(curr) > 0:
                res.append(curr[:])
                return
            for i in range(start, len(digits)):
                for j in relation[digits[i]]:
                    curr += j
                    dfs(digits, i + 1, residue - 1, relation, curr, res)
                    curr = curr[:-1]
        
        curr = ""
        res = []
        dfs(digits, 0, len(digits), relation, curr, res)
        return res

1.9 N-Queens

题目跳转:https://www.lintcode.com/problem/n-queens/description

在这里插入图片描述
在这里插入图片描述

这类题无非按行或按列作为主方向。

这里按行进行递归,以3个条件来剪枝(因行方向肯定不重复,因此不考虑):
1、同一列内不重复,以col储存;
2、同一主对角线方向不重复,以principal_diag储存;
3、同一副对角线方向不重复,以counter_diag储存。

分析剪枝的规律,主对角线方向和副对角线方向的横纵坐标是有规律的。
在这里插入图片描述
图自题解

class Solution:
    """
    @param: n: The number of queens
    @return: All distinct solutions
    """
    def solveNQueens(self, n):
        # write your code here
        # 2020/7/10
        def stack2board(stack, rows):
            return ["{}Q{}".format(("." * stack[i]), ("." * (len(rows) - stack[i] - 1))) for i in rows]
            
        def backTracking(rows, row, col, p_diag, c_diag, stack, res):
            if row == len(rows):
                board = stack2board(stack, rows)
                res.append(board)
                return
            
            for i in rows:
                if i in col or (i - row) in p_diag or (i + row) in c_diag:
                    continue
                col.add(i)
                p_diag.add(i - row)
                c_diag.add(i + row)
                stack.append(rows[i])
                
                backTracking(rows, row + 1, col, p_diag, c_diag, stack, res)
                
                col.remove(i)
                p_diag.remove(i - row)
                c_diag.remove(i + row)
                stack.pop()
        
        rows = [i for i in range(n)]
        stack = []
        col = set()
        principal_diag = set()
        counter_diag = set()
        res = []
        backTracking(rows, 0, col, principal_diag, counter_diag, stack, res)
        return res

1.10 Permutations II

题目跳转:https://www.lintcode.com/problem/permutations-ii/description
在这里插入图片描述
在这里插入图片描述

curr要和nums长度一致,这也是迭代结束的标志,这里可以直接用remain来兼职做结束的条件判断。
remain代表剩余哪个数没用的索引,刚开始时,remain = [0, 1, .., n],本次迭代用了哪个数,就把这个数的索引剔除,给到下一迭代阶段:remain[: i] + remain[i + 1:]
每个迭代的阶段里之所以要循环索引i,是用来对结果去重的(前提是已经nums.sort())。在本次迭代中,ii - 1对应的remain[i]remain[i - 1]紧贴着,因为nums已经排序,如果这两个remian的取得的索引在nums里取值相等,就证明重复了,直接conitnue剪枝。

class Solution:
    """
    @param: :  A list of integers
    @return: A list of unique permutations
    """

    def permuteUnique(self, nums):
        # write your code here
        # 2020/7/10
        def backTracking(nums, remain, curr, res):
            if not len(remain):
                res.append(curr.copy())
                return
            for i, j in enumerate(remain):
                if i > 0 and nums[remain[i]] == nums[remain[i - 1]]:
                    continuea
                curr.append(nums[j])
                backTracking(nums, remain[: i] + remain[i + 1:], curr, res)
                curr.pop()
                
        curr = []
        res = []
        nums.sort()
        remain = [i for i in range(len(nums))]  # indexs of nums
        backTracking(nums, remain, curr, res)
        return res

1.11 Coin Change

题目跳转:https://www.lintcode.com/problem/coin-change/description
在这里插入图片描述
在这里插入图片描述
源自题解,选面值最大的不一定是最优解:[1, 7, 10]对于14的最优解并非10, 1, 1, 1, 1而是7, 7,因此选完面值大的结果也要看面值较小的结果。
这里for循环的是coins的个数,而非索引。且一次性用最多数量的大面值,再逐渐减少大面值的个数。
通过if count + i >= res: continue进行剪枝。

class Solution:
    """
    @param coins: a list of integer
    @param amount: a total amount of money amount
    @return: the fewest number of coins that you need to make up
    """
    def coinChange(self, coins, amount):
        # write your code here
        # 2020/7/13
        def dfs(coins, c_index, residue, count, res):
            if not residue:
                return min(count, res)
            if c_index >= len(coins): return res
            # i是选coins[c_index]的个数,从最多往下减至0
            for i in range(residue // coins[c_index], -1, -1):
                if count + i >= res: continue
                res = dfs(coins, c_index + 1, residue - (i * coins[c_index]), count + i, res)
            return res
            
        coins.sort(reverse=True)
        res = 10001  # 因题目amount不超过10000
        res = dfs(coins, 0, amount, 0, res)
        return res if res != 10001 else -1

2. Data Structure

2.1 Moving Average from Data Stream

题目跳转:https://www.lintcode.com/problem/moving-average-from-data-stream/description

在这里插入图片描述
并不难,但有些细节。
保存self.sum可以减少很多计算量。

class MovingAverage:
    """
    @param: size: An integer
    """
    def __init__(self, size):
        # do intialization if necessary
        self.queue = []
        self.size = size
        self.sum = 0.

    """
    @param: val: An integer
    @return:  
    """
    def next(self, val):
        # write your code here
        # 2020/7/10
        self.queue.append(val)
        self.sum += val
        if len(self.queue) > self.size:
            self.sum -= self.queue.pop(0)
        return self.sum / len(self.queue)
        
# Your MovingAverage object will be instantiated and called as such:
# obj = MovingAverage(size)
# param = obj.next(val)

2.2 Insert Delete GetRandom O(1)

本题简单,仅作记录
题目跳转:https://www.lintcode.com/problem/insert-delete-getrandom-o1/description

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

import random
class RandomizedSet:
    
    def __init__(self):
        # do intialization if necessary
        self.set = []

    """
    @param: val: a value to the set
    @return: true if the set did not already contain the specified element or false
    """
    def insert(self, val):
        # write your code here
        # 2020/7/11
        if val not in self.set:
            self.set.append(val)
            return True
        return False

    """
    @param: val: a value from the set
    @return: true if the set contained the specified element or false
    """
    def remove(self, val):
        # write your code here
        try:
            self.set.remove(val)
            return True
        except Exception as e:
            return False

    """
    @return: Get a random element from the set
    """
    def getRandom(self):
        # write your code here
        return self.set[random.randint(0, len(self.set) - 1)]


# Your RandomizedSet object will be instantiated and called as such:
# obj = RandomizedSet()
# param = obj.insert(val)
# param = obj.remove(val)
# param = obj.getRandom()

2.3 Merge Sorted Array

题目跳转:https://www.lintcode.com/problem/merge-sorted-array/description

在这里插入图片描述
在这里插入图片描述
得益于题目已排序,通过i控制A从后(m+n-1)往前(0)填充,就不用使用额外的内存空间来合并再排序。

class Solution:
    """
    @param: A: sorted integer array A which has m elements, but size of A is m+n
    @param: m: An integer
    @param: B: sorted integer array B which has n elements
    @param: n: An integer
    @return: nothing
    """
    def mergeSortedArray(self, A, m, B, n):
        # write your code here
        # 2020/7/12
        i, m, n = m + n - 1, m - 1, n - 1
        while m >= 0 or n >= 0:
            if (n < 0) or (m >= 0 and A[m] > B[n]):
                A[i] = A[m]
                m -= 1
            else:
                A[i] = B[n]
                n -= 1
            i -= 1

2.4 Intersection of Two Arrays

题目跳转:https://www.lintcode.com/problem/intersection-of-two-arrays/description
在这里插入图片描述
在这里插入图片描述

class Solution:
    """
    @param nums1: an integer array
    @param nums2: an integer array
    @return: an integer array
    """
    def intersection(self, nums1, nums2):
        # write your code here
        # 2020/7/12
        return list(set(nums1) & set(nums2))

3. Binary Tree

二叉搜索树、线段树

3.1 Closest Binary Search Tree Value

题目跳转:https://www.lintcode.com/problem/closest-binary-search-tree-value/description

在这里插入图片描述
在这里插入图片描述

"""
Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""

class Solution:
    """
    @param root: the given BST
    @param target: the given target
    @return: the value in the BST that is closest to the target
    """
    def closestValue(self, root, target):
        # write your code here
        # 2020/7/26
        curr = root
        gap = abs(curr.val - target)
        res = curr.val
        while curr:
            this_gap = abs(curr.val - target)
            if this_gap < gap:
                res = curr.val
                gap = this_gap
            if target < curr.val:
                curr = curr.left
            else:
                curr = curr.right
        return res

3.2 Binary Tree Paths

题目跳转:https://www.lintcode.com/problem/binary-tree-paths/description
在这里插入图片描述
在这里插入图片描述

"""
Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""

class Solution:
    """
    @param root: the root of the binary tree
    @return: all root-to-leaf paths
    """
    def binaryTreePaths(self, root):
        # write your code here
        # 2020/7/26
        def list2str(l):
            s = str(l[0])
            for i in l[1:]:
                s += "->"
                s += str(i)
            return s
        def dfs(node, res, curr):
            curr.append(node.val)
            if not (node.left or node.right):
                res.append(list2str(curr))
                return
            if node.left:
                dfs(node.left, res, curr)
                curr.pop()
            if node.right:
                dfs(node.right, res, curr)
                curr.pop()
        if not root: return []
        res = []
        curr = []
        dfs(root, res, curr)
        return res
        

3.3 Range Sum Query - Mutable

题目跳转:https://www.lintcode.com/problem/range-sum-query-mutable/description

在这里插入图片描述
在这里插入图片描述

思路源自题解,使用了线段树的数据结构,每个叶子节点存储了原数组的元素,每个非叶子节点存储了其子节点的和。
判断l是否在范围内(即是否为左节点),不在则加上并+1。同理,判断r是否在范围内(即是否为右节点),不在则加上并-1

class NumArray:

    def __init__(self, nums):
        """
        :type nums: List[int]
        """
        # 2020/7/12
        self.n = len(nums)
        self.tree = [0] * (2 * self.n - 1)  # 树的最大长度是2n - 1
        # 从n - 1开始,依次把nums放入self.tree
        for i in range(self.n - 1, len(self.tree)):
            self.tree[i] = nums[i - self.n + 1]
        for i in range(self.n - 2, -1, -1):  # range左开右闭,self.n - 2到0(不含-1)
            self.tree[i] = self.tree[2 * i + 1] + self.tree[2 * i + 2]
        

    def update(self, i, val):
        """
        :type i: int
        :type val: int
        :rtype: void
        """
        i += (self.n - 1)
        self.tree[i] = val
        i = (i - 1) // 2
        while i >= 0:
            self.tree[i] = self.tree[2 * i + 1] + self.tree[2 * i + 2]
            i = (i - 1) // 2
            
        

    def sumRange(self, i, j):
        """
        :type i: int
        :type j: int
        :rtype: int
        """
        res = 0
        i += (self.n - 1)
        j += (self.n - 1)
        while i <= j:
            if (i % 2) == 0:
                res += self.tree[i]
                i += 1
            if (j % 2) == 1:
                res += self.tree[j]
                j -= 1
            i = (i - 1) // 2
            j = (j - 1) // 2
        return res
        
# Your NumArray object will be instantiated and called as such:
# obj = NumArray(nums)
# obj.update(i,val)
# param_2 = obj.sumRange(i,j)

4. Hash Table

4.1 Sparse Matrix Multiplication

题目跳转:https://www.lintcode.com/problem/sparse-matrix-multiplication/description

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

class Solution:
    """
    @param A: a sparse matrix
    @param B: a sparse matrix
    @return: the result of A * B
    """
    def multiply(self, A, B):
        # write your code here
        # 2020/7/13
        def compress(matrix):
            cm = {}
            for r in range(len(matrix)):
                for c in range(len(matrix[0])):
                    if matrix[r][c]:
                        cm.setdefault(r, {})[c] = matrix[r][c]
            return cm
        
        # A: [[1,0,0],
        #    [-1,0,3]]
        # B: [[7,0,0],
        #     [0,0,0],
        #     [0,0,1]]
        ca, cb = compress(A), compress(B)
        # ca: {0: {0: 1}, 1: {0: -1, 2: 3}}
        # cb: {0: {0: 7}, 2: {2: 1}}
        C = [[0 for _ in range(len(B[0]))] for _ in range(len(A))]
        # C: [[0, 0, 0], 
        #     [0, 0, 0]]
        for i in ca:  # 遍历A每行,i是A的行号
            for j in ca[i]:  # 遍历本行,j是A的列号,也是B的行号
                for k in cb.get(j, {}):  # 用B的行号去取B的列号k
                    C[i][k] += ca[i][j] * cb[j][k]
                    
        return C

4.2 Subarray Sum

题目跳转:https://www.lintcode.com/problem/subarray-sum/description

在这里插入图片描述
在这里插入图片描述
分析题目,从nums[0]开始累加,当累加结果重复就证明中间的和为0,这里要记录对应索引,故使用Hash记录。

class Solution:
    """
    @param nums: A list of integers
    @return: A list of integers includes the index of the first number and the index of the last number
    """
    def subarraySum(self, nums):
        # write your code here
        # 2020/7/12
        map, prefix_sum = {0: 0}, 0
        for i, n in enumerate(nums):
            prefix_sum += n
            if prefix_sum in map:
                return [map[prefix_sum], i]
            # 注意这里是 i + 1
            map[prefix_sum] = i + 1

注意map[prefix_sum] = i + 1要加一,因为当prefix_sum in map是和子序列开始位置的前一个数的累和相等,所以前一个数应该放后一个数的index,所以i + 1
例如[3, 5, 1, -2, -4],加上-4后相等的是3,而结果是要从5开始,所以3记录的i要加一。

4.3 Longest Palindrome

题目跳转:https://www.lintcode.com/problem/longest-palindrome/description
在这里插入图片描述
在这里插入图片描述

class Solution:
    """
    @param s: a string which consists of lowercase or uppercase letters
    @return: the length of the longest palindromes that can be built
    """
    def longestPalindrome(self, s):
        # write your code here
        # 2020/7/14
        has_odd = False
        res = 0
        dict = {}
        for c in s:
            if c not in dict:
                dict[c] = 0
            dict[c] += 1
        for c, n in dict.items():
            if n % 2 == 1:
                res += (n - 1)
                has_odd = True
            else:
                res += n
        if has_odd: return res + 1
        return res

5. Dynamic Programming(DP)

最重要是找到题目的规律,归纳出状态转移方程,再根据题目的个性化设定边界条件。

5.1 Unique Paths

题目跳转:https://www.lintcode.com/problem/unique-paths/description
在这里插入图片描述
在这里插入图片描述
因只能move right or down,故动态转移方程为:
dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
且首行和首列dp都为1。

class Solution:
    """
    @param m: positive integer (1 <= m <= 100)
    @param n: positive integer (1 <= n <= 100)
    @return: An integer
    """
    def uniquePaths(self, m, n):
        # write your code here
        # 2020/7/13
        # Dynamic Programming
        dp = [[0 for _ in range(n)] for _ in range(m)]
        for i in range(len(dp[0])):
            dp[0][i] = 1
        for i in range(len(dp)):
            dp[i][0] = 1
        for i in range(1, m):
            for j in range(1, n):
                dp[i][j] += (dp[i - 1][j] + dp[i][j - 1])
        return dp[-1][-1]

5.2 Unique Paths II

题目跳转:https://www.lintcode.com/problem/unique-paths-ii/description
在这里插入图片描述
在这里插入图片描述
相比于Unique Paths,多了障碍(标为1),动态转移方程为:
dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
基于障碍,本题有如下特性:

  1. 首行和首列若遇障碍,障碍及后面dp=0
  2. 有障碍的地方dp=0
class Solution:
    """
    @param obstacleGrid: A list of lists of integers
    @return: An integer
    """
    def uniquePathsWithObstacles(self, obstacleGrid):
        # write your code here
        # 2020/7/13
        m, n = len(obstacleGrid[0]), len(obstacleGrid)
        dp = [[0 for _ in range(m)] for _ in range(n)]
        for i in range(m):
            if obstacleGrid[0][i]: break
            dp[0][i] = 1
        for i in range(n):
            if obstacleGrid[i][0]: break
            dp[i][0] = 1
        for i in range(1, m):
            for j in range(1, n):
                if not obstacleGrid[j][i]:
                    dp[j][i] += (dp[j - 1][i] + dp[j][i - 1])
        return dp[-1][-1]

5.3 Maximum Subarray

题目跳转:https://www.lintcode.com/problem/maximum-subarray/description
在这里插入图片描述
在这里插入图片描述

class Solution:
    """
    @param nums: A list of integers
    @return: A integer indicate the sum of max subarray
    """
    def maxSubArray(self, nums):
        # write your code here
        # 2020/7/12
        sum, ans = 0, nums[0]
        for n in nums:
            if sum <= 0:
                sum = n
            else:
                sum += n
            ans = max(ans, sum)
        return ans

sumnum之前不管多少个数的累加,如果当前 sum<=0,对于把num变大没有帮助了,直接sum=num,反之就加上去sum+=numsum累死累活遍历各个num,若<=0还得被嫌弃,而ans就比较无情了,只取自身和sum的最大值max(sum, ans)。 (ans:身不由己啊…)
每个遍历的状态都取决于上一状态,也有点动态规划的感觉。

5.4 Maximum Submatrix

题目跳转:https://www.lintcode.com/problem/maximum-submatrix/description

在这里插入图片描述
在这里插入图片描述

class Solution:
    """
    @param matrix: the given matrix
    @return: the largest possible sum
    """
    def maxSubmatrix(self, matrix):
        # write your code here
        # 2020/7/12
        if not len(matrix): return 0
        n = len(matrix[0])
        if not n: return 0
        ans = matrix[0][0]
        tmp = [0 for _ in range(n)]
        
        for i in range(n):  # 第i行
            for z in range(n):  # 首行换行后,tmp每个值重新累加
                tmp[z] = 0
            for j in range(i, n):  # 第j行
                # j每次换行,sum_和ans_j都得重置,本行结束后再更新ans=max(ans, ans_j)
                sum_ = 0
                ans_j = tmp[0] + matrix[j][0]
                for k in range(n):  # 遍历行内累计值
                    tmp[k] += matrix[j][k]
                    # if sum_ < 0: sum_ = tmp[k], else: sum_ += tmp[k]
                    sum_ = max(sum_ + tmp[k], tmp[k])  
                    ans_j = max(sum_, ans_j)
                ans = max(ans, ans_j)
        return ans

思路源自题解,主要把二维压缩成一维,剩余解法类似题目Maximum Subarray

5.5 Climbing Stairs

题目跳转:https://www.lintcode.com/problem/climbing-stairs/description

在这里插入图片描述
在这里插入图片描述
因只能跳12步,故动态转移方程为:
dp[i] = dp[i - 2] + dp[i - 1]
根据先验知识初始化dp[1]=1dp[2]=2
这里dp[0]无实际意义,闲置。

class Solution:
    """
    @param n: An integer
    @return: An integer
    """
    def climbStairs(self, n):
        # write your code here
        # 2020/7/13
        if n == 0: return 0
        if n == 1: return 1
        dp = [0 for _ in range(n + 1)]
        dp[1], dp[2] = 1, 2
        for i in range(3, n + 1):
            dp[i] = dp[i - 2] + dp[i - 1]
        return dp[-1]

5.6 Minimum Path Sum

题目跳转:https://www.lintcode.com/problem/minimum-path-sum/description

在这里插入图片描述
在这里插入图片描述
动态转移转移方程可见代码:

class Solution:
    """
    @param grid: a list of lists of integers
    @return: An integer, minimizes the sum of all numbers along its path
    """
    def minPathSum(self, grid):
        # write your code here
        # 2020/7/13
        m, n = len(grid[0]), len(grid)
        dp = [[0 for _ in range(m)] for _ in range(n)]
        dp[0][0] = grid[0][0]
        for i in range(1, m):
            dp[0][i] = dp[0][i - 1] + grid[0][i]
        for i in range(1, n):
            dp[i][0] = dp[i - 1][0] + grid[i][0]
            
        for i in range(1, n):
            for j in range(1, m):
                dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j]
        return dp[-1][-1]

5.7 Perfect Squares

题目跳转:https://www.lintcode.com/problem/perfect-squares/description
在这里插入图片描述
在这里插入图片描述
动态转移方程如代码。
因前三i的个数均为自身dp[i]=i,故i4开始遍历。

class Solution:
    """
    @param n: a positive integer
    @return: An integer
    """
    def numSquares(self, n):
        # write your code here
        # 2020/7/13
        dp = [i for i in range(n + 1)]
        for i in range(4, n + 1):
            for j in range(1, i):  # 这里的上限无所谓,后面会用条件判断break
                if i - j * j < 0: break
                dp[i] = min(dp[i], dp[i - j * j] + 1)
        return dp[n]

5.8 Jump Game

题目跳转:https://www.lintcode.com/problem/jump-game/description
在这里插入图片描述
在这里插入图片描述
思路源自题解i+A[i]是这一格能跳的最远距离,k是至今能走的最远距离,最远距离之前的每个格子都能作为起跳点,并不断更新k,若i超出了k,证明无法抵达终点。

class Solution:
    """
    @param A: A list of integers
    @return: A boolean
    """
    def canJump(self, A):
        # write your code here
        # 2020/7/14
        k = 0
        for i in range(len(A)):
            if i > k: return False
            k = max(k, i + A[i])
        return True

5.9 Triangle

题目跳转:https://www.lintcode.com/problem/triangle/description

在这里插入图片描述
在这里插入图片描述
从top不断加到bottom,排除最左和最右的边界条件,选上一层相邻两个数较小的来加。triangle_[i][j] += min(triangle_[i - 1][j - 1], triangle_[i - 1][j])

class Solution:
    """
    @param triangle: a list of lists of integers
    @return: An integer, minimum path sum
    """
    def minimumTotal(self, triangle):
        # write your code here
        # 2020/7/13
        triangle_ = triangle[:]
        for i in range(1, len(triangle_)):
            for j in range(len(triangle_[i])):
                if j == 0:
                    triangle_[i][j] += triangle_[i - 1][j]
                elif j == len(triangle_[i]) - 1:
                    triangle_[i][j] += triangle_[i - 1][j - 1]
                else:
                    triangle_[i][j] += min(triangle_[i - 1][j - 1], triangle_[i - 1][j])
        return min(triangle_[-1])

5.10 Longest Increasing Subsequence

题目跳转:https://www.lintcode.com/problem/longest-increasing-subsequence/description

在这里插入图片描述
在这里插入图片描述
遍历i,并让dp[i]等于前面比nums[i]小的数里,dp最大的值加一。
因答案不一定在dp的末尾,所以每次dp[i]确定后,都取max(dp[i], res)

class Solution:
    """
    @param nums: An integer array
    @return: The length of LIS (longest increasing subsequence)
    """
    def longestIncreasingSubsequence(self, nums):
        # write your code here
        # 2020/7/14
        if not len(nums): return 0
        res = 0
        dp = [0] * len(nums)
        dp[0] = 1
        for i in range(1, len(nums)):
            for j in range(i):
                if nums[i] > nums[j]:
                    dp[i] = max(dp[i], dp[j])
            dp[i] += 1
            res = max(dp[i], res)
        return res

5.11 Longest Palindromic Substring

题目跳转:https://www.lintcode.com/problem/longest-palindromic-substring/description

在这里插入图片描述
在这里插入图片描述
长度为1和2的子串就像种子,长度再长一些的就要看他内部的子串是否为回文串。

class Solution:
    """
    @param s: input string
    @return: the longest palindromic substring
    """
    def longestPalindrome(self, s):
        # write your code here
        # 2020/7/15
        if not len(s): return ""
        dp = [[False for _ in range(len(s))] for _ in range(len(s))]
        head, tail = 0, 0
        for i in range(len(s)):  # gap between head and tail
            for j in range(len(s) - i):
                if s[j] == s[j + i] and (i < 2 or dp[j + 1][j + i - 1]):
                    dp[j][j + i] = True
                    if i > tail - head:
                        head = j
                        tail = j + i
        return s[head: tail + 1]

在华为机试也遇到同样问题了,用DP方式会超时,于是借鉴了讨论区的回答:

因为是找最长回文串,那么maxlen是可以潇洒地增大,而且字符串前面如果maxlen已经变长了,后面就不用再判断短的回文串了。
而且长的回文串也是基于短回文串的,所以后面都判断[i-maxlen-1: i+1][i-maxlen: i+1]就好了。
第一种条件是当imaxlen不相等,即回文串没有顶到最前面的时候,会试探性向前多一位。
第二种条件是为前者兜底的,试探不了的话,就按照保守的长度(比maxlen长一位)去判断。
总而言之就是深得了回文串的精髓。

def main2(string):
    maxlen = 0
    for i in range(len(string)):
        if i-maxlen >= 1 and string[i-maxlen-1: i+1] == string[i-maxlen-1: i+1][::-1]:
            maxlen += 2
        elif i-maxlen >= 0 and string[i-maxlen: i+1] == string[i-maxlen: i+1][::-1]:
            maxlen += 1
    return maxlen

if __name__ == "__main__":
    while True:
        try:
            string = input()
        except:
            break
        res = main2(string)
        print(res)

5.12 购物单问题

题目跳转:https://www.nowcoder.com/practice/f9c6f980eeec43ef85be20755ddbeaf4?tpId=37&&tqId=21239&rp=1&ru=/ta/huawei/&qru=/ta/huawei/question-ranking
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
解题思路与实现~:华为机试:购物单问题(动态规划)

6. Heap

寻找最xx的k个值,循环调取最值(Merge问题),使用 堆结构(Heap) 可以很好解决这类问题。

6.1 K Closest Points

题目跳转:https://www.lintcode.com/problem/k-closest-points/description

在这里插入图片描述
在这里插入图片描述
heapq.nsmallestheapq.nlargest已经有比较完善的解决方案,其中lambda可以适配个性化的数据结构。

import heapq
"""
Definition for a point.
class Point:
    def __init__(self, a=0, b=0):
        self.x = a
        self.y = b
"""

class Solution:
    """
    @param points: a list of points
    @param origin: a point
    @param k: An integer
    @return: the k closest points
    """
    def kClosest(self, points, origin, k):
        # write your code here
        # 2020/7/11
        # return heapq.nsmallest(k, points, lambda p: [(p.x - origin.x) ** 2 + (p.y - origin.y) ** 2, p.x, p.y])
        heap_dis, res, dis2point = [], [], {}
        for p in points:
            d = (p.x - origin.x) ** 2 + (p.y - origin.y) ** 2
            if d not in dis2point:
                dis2point[d] = [p]
                heapq.heappush(heap_dis, d)
            else:
                dis2point[d].append(p)
                
        while len(res) < k:
            d = heapq.heappop(heap_dis)
            if len(dis2point[d]) + len(res) <= k:
                res += sorted(dis2point[d], key=lambda p: [p.x, p.y])
            else:
                res += sorted(dis2point[d], key=lambda p: [p.x, p.y])[:(k - len(res))]
        return res

6.2 Merge K Sorted Lists

题目跳转:https://www.lintcode.com/problem/merge-k-sorted-lists/description

在这里插入图片描述
得益于每个链表都已排序,直接把每个链接的头结点(最小值)放进小顶堆,不断取了放新的进来。
题解还可使用分治法,先mark了。

import heapq
"""
Definition of ListNode
class ListNode(object):

    def __init__(self, val, next=None):
        self.val = val
        self.next = next
"""
class Solution:
    """
    @param lists: a list of ListNode
    @return: The head of one sorted list.
    """
    def mergeKLists(self, lists):
        # write your code here
        # 2020/7/11
        origin = ListNode(0)
        p = origin
        l = lists
        heads = []
        for idx in range(len(l)):
            if l[idx]:
                heapq.heappush(heads, (l[idx].val, idx))
                l[idx] = l[idx].next
        while heads:
            val, idx = heapq.heappop(heads)
            p.next = ListNode(val)
            p = p.next
            if l[idx]:
                heapq.heappush(heads, (l[idx].val, idx))
                l[idx] = l[idx].next
        return origin.next

6.3 Merge Two Sorted Interval Lists

题目跳转:https://www.lintcode.com/problem/merge-two-sorted-interval-lists/description

在这里插入图片描述
在这里插入图片描述
Merge问题,和Merge K Sorted Lists差不多,都是用小顶堆处理(前提是各子序列已排序)。
本题是要start按序取出,判断是否在res的区间内,在则合并,不在则新增。

import heapq
"""
Definition of Interval.
class Interval(object):
    def __init__(self, start, end):
        self.start = start
        self.end = end
"""

class Solution:
    """
    @param list1: one of the given list
    @param list2: another list
    @return: the new sorted list of interval
    """
    def mergeTwoInterval(self, list1, list2):
        # write your code here
        # 2020/7/11
        ls = [list1, list2]
        heads = []
        res = []
        for idx, l in enumerate(ls):
            if len(l):
                heapq.heappush(heads, (l[0].start, l[0].end, idx))
                l.pop(0)
        while heads:
            start, end, idx = heapq.heappop(heads)
            if not len(res):
                res.append(Interval(start, end))
            elif start <= res[-1].end:
                res[-1].end = max(res[-1].end, end)
            else:
                res.append(Interval(start, end))
            if len(ls[idx]):
                heapq.heappush(heads, (ls[idx][0].start, ls[idx][0].end, idx))
                ls[idx].pop(0)
        return res

7. Binary Search & Log(n) Algorithm

针对给定数组有一定的规律的(如已排序、山峰状等),可以根据规律做Binary Search。
或针对题目的规律,实现二二拆解,达到Log(n)的复杂度。

7.1 Maximum Number in Mountain Sequence

题目跳转:https://www.lintcode.com/problem/maximum-number-in-mountain-sequence/description
在这里插入图片描述
在这里插入图片描述
循环到最后剩余nums[head]nums[tail],返回两者的最大值。

class Solution:
    """
    @param nums: a mountain sequence which increase firstly and then decrease
    @return: then mountain top
    """
    def mountainSequence(self, nums):
        # write your code here
        # 2020/7/15
        head, tail = 0, len(nums) - 1
        while head < tail - 1:
            mid = head + (tail - head) // 2
            if nums[mid] > nums[mid - 1]:
                head = mid
            else:
                tail = mid
        return max(nums[head], nums[tail])

7.2 Pow(x, n)

题目跳转:https://www.lintcode.com/problem/powx-n/description
在这里插入图片描述
在这里插入图片描述
记得考虑n >0的情况。

class Solution:
    """
    @param x {float}: the base number
    @param n {int}: the power number
    @return {float}: the result
    """
    def myPow(self, x, n):
        # write your code here
        # 2020/7/16
        if n < 0:
            n = -n
            x = 1 / x
        if n == 1: return x
        if n == 0: return 1
        if n % 2 == 0:
            return self.myPow(x * x, n / 2)
        return self.myPow(x * x, n // 2) * x

7.3 Find Minimum in Rotated Sorted Array

题目跳转:https://www.lintcode.com/problem/find-minimum-in-rotated-sorted-array/description
在这里插入图片描述
在这里插入图片描述

题解讲得非常好,梳理了Binary Search的分析过程。只要画出“左、中、右”的相互关系,就能推断出两个指针的变化规律。
而且因mid = head + (tail - head) // 2是更接近head的,即mid >= headmid < right,所以head=mid+1才有可能跳出循环,而right=mid则无所谓。

class Solution:
    """
    @param nums: a rotated sorted array
    @return: the minimum number in the array
    """
    def findMin(self, nums):
        # write your code here
        # 2020/7/16
        head, tail = 0, len(nums) - 1
        while head < tail:
            mid = head + (tail - head) // 2
            if nums[mid] < nums[tail]:
                tail = mid
            else:
                head = mid + 1
        return nums[head]

7.4 Fast Power

题目跳转:https://www.lintcode.com/problem/fast-power/description
在这里插入图片描述
根据公式: a n % b = ( a n / 2 % b ⋅ a n / 2 % b ) % b a^n \% b = (a^{n/2} \% b \cdot a^{n/2} \% b) \% b an%b=(an/2%ban/2%b)%b
res就会变得很小(比b小)。

class Solution:
    """
    @param a: A 32bit integer
    @param b: A 32bit integer
    @param n: A 32bit integer
    @return: An integer
    """
    def fastPower(self, a, b, n):
        # write your code here
        # 2020/7/16
        if n == 0: return 1 % b
        if n == 1: return a % b
        if n % 2 == 0:
            res = self.fastPower(a, b, n / 2)
            return (res * res) % b
        res = self.fastPower(a, b, n // 2)
        a %= b
        return (a * res * res) % b

7.5 Find Peak Element

题目跳转:https://www.lintcode.com/problem/find-peak-element/description
在这里插入图片描述
在这里插入图片描述

画出“中,中+1”的关系后,即可找出规律。再分析边界条件,确定循环可收敛。

class Solution:
    """
    @param A: An integers array.
    @return: return any of peek positions.
    """
    def findPeak(self, A):
        # write your code here
        # 2020/7/16
        left, right = 0, len(A) - 1
        while left < right:
            mid = left + (right - left) // 2
            if A[mid] < A[mid + 1]:
                left = mid + 1
            else:
                right = mid
        return left

7.6 First Bad Version

题目跳转:https://www.lintcode.com/problem/first-bad-version/description
在这里插入图片描述
在这里插入图片描述

SVNRepo.isBadVersion(mid) is True,就像左找,并且不用担心miss了答案;反之,则向右找,因SVNRepo.isBadVersion(mid) is False,那left=mid+1也不担心miss了答案。
反正只要找好规律,再确保干掉边界条件,循环能收敛就好。

#class SVNRepo:
#    @classmethod
#    def isBadVersion(cls, id)
#        # Run unit tests to check whether verison `id` is a bad version
#        # return true if unit tests passed else false.
# You can use SVNRepo.isBadVersion(10) to check whether version 10 is a 
# bad version.
class Solution:
    """
    @param n: An integer
    @return: An integer which is the first bad version.
    """
    def findFirstBadVersion(self, n):
        # write your code here
        # 2020/7/16
        left, right = 1, n
        while left < right:
            mid = left + (right - left) // 2
            if SVNRepo.isBadVersion(mid):
                right = mid
            else:
                left = mid + 1
        return left

7.7 Search in Rotated Sorted Array

题目跳转:https://www.lintcode.com/problem/search-in-rotated-sorted-array/description
在这里插入图片描述
在这里插入图片描述

先判断在mid的左边还是右边有序,再看target是否在有序区间内,根据结果移动leftright

class Solution:
    """
    @param A: an integer rotated sorted array
    @param target: an integer to be searched
    @return: an integer
    """
    def search(self, A, target):
        # write your code here
        # 2020/7/17
        if not len(A): return -1
        left, right = 0, len(A) - 1
        while left < right:
            mid = left + (right - left) // 2
            if A[left] <= A[mid]:  # 左有序
                if target >= A[left] and target <= A[mid]:
                    right = mid
                else:
                    left = mid + 1
            else:  # 右有序
                if target >= A[mid] and target <= A[right]:
                    left = mid
                else:
                    right = mid - 1
        if A[left] == target: return left
        return -1

8. Stack

8.1 Longest Valid Parentheses

题目跳转:https://www.lintcode.com/problem/longest-valid-parentheses/description
在这里插入图片描述
思路自LeetCode评论区。先用Stack校验String里括号的有效性,把有效的括号都标为0,无效的为1。
最后只需计算最长的0串长度即可。
(果然括号这类问题还是用Stack最舒服…)
第一次用C++做题,要慢慢习惯~~

class Solution {
public:
    /**
     * @param s: a string
     * @return: return a integer
     */
    int longestValidParentheses(string &s) {
        // write your code here
        // 2020/10/17
        // ()   (())   ()(())()
        int res = 0;
        int i = 0;
        int len = 0;
        stack<int> st;
        vector<bool> mark(s.length());
        for( i = 0; i < mark.size(); i++ ) mark[i] = false;
        for( i = 0; i < s.length(); i++ ) {
            if( s[i] == '(' ) st.push(i);
            else { // ')'
                if( st.empty() ) mark[i] = true;
                else st.pop();
            }
        }
        while( !st.empty() ) {
            mark[st.top()] = true;
            st.pop();
        }
        for( i = 0; i < mark.size(); i++ ) {
            if( !mark[i] ) {
                len++;
            } else {
                len = 0;
            }
            res = max(res, len);
        }
        return res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-468%20%2F%20468-ff69b4.svg) Up to date (2016-12-18), there are `447` Algorithms / `13` Database / `4` Shell / `4` Draft questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. Here is the classification of all `468` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "馃摉" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions.) ## Algorithms * [Bit Manipulation](https://github.com/kamyu104/LeetCode#bit-manipulation) * [Array](https://github.com/kamyu104/LeetCode#array) * [String](https://github.com/kamyu104/LeetCode#string) * [Linked List](https://github.com/kamyu104/LeetCode#linked-list) * [Stack](https://github.com/kamyu104/LeetCode#stack) * [Queue](https://github.com/kamyu104/LeetCode#queue) * [Heap](https://github.com/kamyu104/LeetCode#heap) * [Tree](https://github.com/kamyu104/LeetCode#tree) * [Hash Table](https://github.com/kamyu104/LeetCode#hash-table) * [Data Structure](https://github.com/kamyu104/LeetCode#data-structure) * [Math](https://github.com/kamyu104/LeetCode#math) * [Two Pointers](https://github.com/kamyu104/LeetCode#two-pointers) * [Sort](https://github.com/kamyu104/LeetCode#sort) * [Recursion](https://github.com/kamyu104/LeetCode#recursion) * [Binary Search](https://github.com/kamyu104/LeetCode#binary-search) * [Binary Search Tree](https://github.com/kamyu104/LeetCode#binary-search-tree) * [Breadth-First Search](https://github.com/kamyu104/LeetCode#breadth-first-search) * [Depth-First Search](https://github.com/kamyu104/LeetCode#depth-first-search) * [Backtracking](https://github.com/kamyu104/LeetCode#backtracking) * [Dynamic Programming](https://github.com/kamyu104/LeetCode#dynamic-programming) * [Greedy](https://github.com/kamyu104/LeetCode#greedy) * [Design](https://github.com/kamyu104/LeetCode#design) ## Database * [SQL](https://github.com/kamyu104/LeetCode#sql) ## Shell * [Shell Script](https://github.com/kamyu104/LeetCode#shell-script) ## Bit Manipulation | # | Title | Solution | Time | Space | Difficulty | Tag | Note| |-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------|-----| 136 | [Single Number](https://leetcode.com/problems/single-number/) | [C++](./C++/single-number.cpp) [Python](./Python/single-number.py) | _O(n)_ | _O(1)_ | Easy ||| 137 | [Single Number II](https://leetcode.com/problems/single-number-ii/) | [C++](./C++/single-number-ii.cpp) [Python](./Python/single-number-ii.py) | _O(n)_ | _O(1)_ | Medium ||| 190 | [Reverse Bits](https://leetcode.com/problems/reverse-bits/) | [C++](./C++/reverse-bits.cpp) [Python](./Python/reverse-bits.py) | _O(1)_ | _O(1)_ | Easy ||| 191 |[Number of 1 Bits](https://leetcode.com/problems/number-of-1-bits/) | [C++](./C++/number-of-1-bits.cpp) [Python](./Python/number-of-1-bits.py) | _O(1)_ | _O(1)_ | Easy ||| 201 | [Bitwise AND of Numbers Range](https://leetcode.com/problems/bitwise-and-of-numbers-range/) | [C++](./C++/bitwise-and-of-numbers-range.cpp) [Python](./Python/bitwise-and-of-numbers-range.py) | _O(1)_ | _O(1)_ | Medium || 231 | [Power of Two](https://leetcode.com/problems/power-of-two/) | [C++](./C++/power-of-two.cpp) [Python](./Python/power-of-two.py) | _O(1)_ | _O(1)_ | Easy | LintCode | 260 | [Single Number III](https://leetcode.com/problems/single-number-iii/) | [C++](./C++/single-number-iii.cpp) [Python](./Python/single-number-iii.py) | _O(n)_ | _O(1)_ | Medium || 268| [Missing Number](https://leetcode.com/problems/missing-number/) | [C++](./C++/missing-number.cpp) [Python](./Python/missing-number.py) | _O(n)_ | _O(1)_ | Medium | LintCode || 318| [Maximum Product of Word Lengths](https://leetcode.com/problems/maximum-product-of-word-lengths/) | [C++](./C++/maximum-product-of-word-lengths.cpp) [Python](./Python/maximum-product-of-word-lengths.py) | _O(n)_ ~ _O(n^2)_ | _O(n)_ | Medium || Bit Manipulation, Counting Sort, Pruning| 342 | [Power of Four](https://leetcode.com/problems/power-of-four/) | [C++](./C++/power-of-four.cpp) [Python](./Python/power-of-four.py) | _O(1)_ | _O(1)_ | Easy | | 371 | [Sum of Two Integers](https://leetcode.com/problems/sum-of-two-integers/) | [C++](./C++/sum-of-two-integers.cpp) [Python](./Python/sum-of-two-integers.py) | _O(1)_ | _O(1)_ | Easy | LintCode | 389 | [Find the Difference](https://leetcode.com/problems/find-the-difference/) | [C++](./C++/find-the-difference.cpp) [Python](./Python/find-the-difference.py) | _O(n)_ | _O(1)_ | Easy | | 393 | [UTF-8 Validation](https://leetcode.com/problems/utf-8-validation/) | [C++](./C++/utf-8-validation.cpp) [Python](./Python/utf-8-validation.py) | _O(n)_ | _O(1)_ | Medium | | 401 | [Binary Watch](https://leetcode.com/problems/binary-watch/) | [C++](./C++/binary-watch.cpp) [Python](./Python/binary-watch.py) | _O(1)_ | _O(1)_ | Easy | | 411 | [Minimum Unique Word Abbreviation](https://leetcode.com/problems/minimum-unique-word-abbreviation/) | [C++](./C++/minimum-unique-word-abbreviation.cpp) [Python](./Python/minimum-unique-word-abbreviation.py) | _O(2^n)_ | _O(n)_ | Hard | 馃摉 | 421 | [Maximum XOR of Two Numbers in an Array](https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array/) | [C++](./C++/maximum-xor-of-two-numbers-in-an-array.cpp) [Python](./Python/maximum-xor-of-two-numbers-in-an-array.py) | _O(n)_ | _O(1)_ | Medium || 461 | [Hamming Distance](https://leetcode.com/problems/hamming-distance/) | [C++](./C++/hamming-distance.cpp) [Python](./Python/hamming-distance.py) | _O(1)_ | _O(1)_ | Easy || 462 | [Minimum Moves to Equal Array Elements II](https://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii/) | [C++](./C++/minimum-moves-to-equal-array-elements-ii.cpp) [Python](./Python/minimum-moves-to-equal-array-elements-ii.py) | _O(n)_ on average | _O(1)_ | Medium || 477 | [Total Hamming Distance](https://leetcode.com/problems/total-hamming-distance/) | [C++](./C++/total-hamming-distance.cpp) [Python](./Python/total-hamming-distance.py) | _O(n)_ | _O(1)_ | Medium || ## Array | # | Title | Solution | Time | Space | Difficulty | Tag | Note| |-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------|-----| 15 | [3 Sum](https://leetcode.com/problems/3sum/) | [C++](./C++/3sum.cpp) [Python](./Python/3sum.py) | _O(n^2)_ | _O(1)_ | Medium || Two Pointers 16 | [3 Sum Closest](https://leetcode.com/problems/3sum-closest/) | [C++](./C++/3sum-closest.cpp) [Python](./Python/3sum-closest.py) | _O(n^2)_ | _O(1)_ | Medium || Two Pointers 18| [4 Sum](https://leetcode.com/problems/4sum/) | [C++](./C++/4sum.cpp) [Python](./Python/4sum.py) | _O(n^3)_ | _O(1)_ | Medium || Two Pointers 26 | [Remove Duplicates from Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/)| [C++](./C++/remove-duplicates-from-sorted-array.cpp) [Python](./Python/remove-duplicates-from-sorted-array.py) | _O(n)_ | _O(1)_ | Easy || Two Pointers 27 | [Remove Element](https://leetcode.com/problems/remove-element/) | [C++](./C++/remove-element.cpp) [Python](./Python/remove-element.py) | _O(n)_ | _O(1)_ | Easy || 31 | [Next Permutation](https://leetcode.com/problems/next-permutation/)| [C++](./C++/next-permutation.cpp) [Python](./Python/next-permutation.py) | _O(n)_ | _O(1)_ | Medium || Tricky 41 | [First Missing Positive](https://leetcode.com/problems/first-missing-positive/)| [C++](./C++/first-missing-positive.cpp) [Python](./Python/first-missing-positive.py) | _O(n)_ | _O(1)_ | Hard || Tricky 48 | [Rotate Image](https://leetcode.com/problems/rotate-image/) | [C++](./C++/rotate-image.cpp) [Python](./Python/rotate-image.py) | _O(n^2)_ | _O(1)_ | Medium || 54 | [Spiral Matrix](https://leetcode.com/problems/spiral-matrix/) | [C++](./C++/spiral-matrix.cpp) [Python](./Python/spiral-matrix.py) | _O(m * n)_ | _O(1)_ | Medium || 59 | [Spiral Matrix II](https://leetcode.com/problems/spiral-matrix-ii/) | [C++](./C++/spiral-matrix-ii.cpp) [Python](./Python/spiral-matrix-ii.py) | _O(n^2)_ | _O(1)_ | Medium || 66 | [Plus One](https://leetcode.com/problems/plus-one/) | [C++](./C++/plus-one.cpp) [Python](./Python/plus-one.py) | _O(n)_ | _O(1)_ | Easy || 73 | [Set Matrix Zeroes](https://leetcode.com/problems/set-matrix-zeroes/) | [C++](./C++/set-matrix-zeroes.cpp) [Python](./Python/set-matrix-zeroes.py) | _O(m * n)_ | _O(1)_ | Medium || 80 | [Remove Duplicates from Sorted Array II](https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/)| [C++](./C++/remove-duplicates-from-sorted-array-ii.cpp) [Python](./Python/remove-duplicates-from-sorted-array-ii.py) | _O(n)_ | _O(1)_ | Medium || Two Pointers 118 | [Pascal's Triangle](https://leetcode.com/problems/pascals-triangle/)| [C++](./C++/pascals-triangle.cpp) [Python](./Python/pascals-triangle.py) | _O(n^2)_ | _O(1)_ | Easy || 119 | [Pascal's Triangle II](https://leetcode.com/problems/pascals-triangle-ii/)| [C++](./C++/pascals-triangle-ii.cpp) [Python](./Python/pascals-triangle-ii.py) | _O(n^2)_ | _O(1)_ | Easy || 121 | [Best Time to Buy and Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/)| [C++](./C++/best-time-to-buy-and-sell-stock.cpp) [Python](./Python/best-time-to-buy-and-sell-stock.py) | _O(n)_ | _O(1)_ | Easy || 128 | [Longest Consecutive Sequence](https://leetcode.com/problems/longest-consecutive-sequence/)| [C++](./C++/longest-consecutive-sequence.cpp) [Python](./Python/longest-consecutive-sequence.py) | _O(n)_ | _O(n)_ | Hard || Tricky 157 | [Read N Characters Given Read4](https://leetcode.com/problems/read-n-characters-given-read4/) | [C++](./C++/read-n-characters-given-read4.cpp) [Python](./Python/read-n-characters-given-read4.py) | _O(n)_ | _O(1)_ | Easy |馃摉| 158 | [Read N Characters Given Read4 II - Call multiple times](https://leetcode.com/problems/read-n-characters-given-read4-ii-call-multiple-times/) | [C++](./C++/read-n-characters-given-read4-ii-call-multiple-times.cpp) [Python](./Python/read-n-characters-given-read4-ii-call-multiple-times.py) | _O(n)_ | _O(1)_ | Hard |馃摉| 163 | [Missing Ranges](https://leetcode.com/problems/missing-ranges/)| [C++](./C++/missing-ranges.cpp) [Python](./Python/missing-ranges.py) | _O(n)_ | _O(1)_ | Medium | 馃摉 | 169 | [Majority Element](https://leetcode.com/problems/majority-element/) | [C++](./C++/majority-element.cpp) [Python](./Python/majority-element.py) | _O(n)_ | _O(1)_ | Easy | 189 | [Rotate Array](https://leetcode.com/problems/rotate-array/) | [C++](./C++/rotate-array.cpp) [Python](./Python/rotate-array.py) | _O(n)_ | _O(1)_ | Easy || 209 | [Minimum Size Subarray Sum](https://leetcode.com/problems/minimum-size-subarray-sum/) | [C++](./C++/minimum-size-subarray-sum.cpp) [Python](./Python/minimum-size-subarray-sum.py) | _O(n)_ | _O(1)_ | Medium | | Binary Search 215 | [Kth Largest Element in an Array](https://leetcode.com/problems/kth-largest-element-in-an-array/) | [C++](./C++/kth-largest-element-in-an-array.cpp) [Python](./Python/kth-largest-element-in-an-array.py)| _O(n)_ ~ _O(n^2)_ | _O(1)_ | Medium | EPI| 228 | [Summary Ranges](https://leetcode.com/problems/summary-ranges/) | [C++](./C++/summary-ranges.cpp) [Python](./Python/summary-ranges.py)| _O(n)_ | _O(1)_ | Medium | | 229 | [Majority Element II](https://leetcode.com/problems/majority-element-ii/) | [C++](./C++/majority-element-ii.cpp) [Python](./Python/majority-element-ii.py) | _O(n)_ | _O(1)_ | Medium | | 238 | [Product of Array Except Self](https://leetcode.com/problems/product-of-array-except-self/) | [C++](./C++/product-of-array-except-self.cpp) [Python](./Python/product-of-array-except-self.py) | _O(n)_ | _O(1)_ | Medium | LintCode | 240 | [Search a 2D Matrix II](https://leetcode.com/problems/search-a-2d-matrix-ii/) | [C++](./C++/search-a-2d-matrix-ii.cpp) [Python](./Python/search-a-2d-matrix-ii.py) | _O(m + n)_ | _O(1)_ | Medium | EPI, LintCode | 243| [Shortest Word Distance](https://leetcode.com/problems/shortest-word-distance/) | [C++](./C++/shortest-word-distance.cpp) [Python](./Python/shortest-word-distance.py) | _O(n)_ | _O(1)_ | Easy |馃摉|| 245| [Shortest Word Distance III](https://leetcode.com/problems/shortest-word-distance-iii/) | [C++](./C++/shortest-word-distance-iii.cpp) [Python](./Python/shortest-word-distance-iii.py) | _O(n)_ | _O(1)_ | Medium |馃摉|| 251| [Flatten 2D Vector](https://leetcode.com/problems/flatten-2d-vector/) | [C++](./C++/flatten-2d-vector.cpp) [Python](./Python/flatten-2d-vector.py) | _O(1)_ | _O(1)_ | Medium |馃摉|| 277| [Find the Celebrity](https://leetcode.com/problems/find-the-celebrity/) | [C++](./C++/find-the-celebrity.cpp) [Python](./Python/find-the-celebrity.py) | _O(n)_ | _O(1)_ | Medium |馃摉, EPI || 289| [Game of Life](https://leetcode.com/problems/game-of-life/) | [C++](./C++/game-of-life.cpp) [Python](./Python/game-of-life.py) | _O(m * n)_ | _O(1)_ | Medium ||| 293| [Flip Game](https://leetcode.com/problems/flip-game/) | [C++](./C++/flip-game.cpp) [Python](./Python/flip-game.py) | _O(n * (c+1))_ | _O(1)_ | Easy |馃摉|| 296| [Best Meeting Point](https://leetcode.com/problems/best-meeting-point/) | [C++](./C++/best-meeting-point.cpp) [Python](./Python/best-meeting-point.py) | _O(m * n)_ | _O(m + n)_ | Hard |馃摉|| 311| [Sparse Matrix Multiplication](https://leetcode.com/problems/sparse-matrix-multiplication/) | [C++](./C++/sparse-matrix-multiplication.cpp) [Python](./Python/sparse-matrix-multiplication.py) | _O(m * n * l)_ | _O(m * l)_ | Medium |馃摉|| 334| [Increasing Triplet Subsequence](https://leetcode.com/problems/increasing-triplet-subsequence/) | [C++](./C++/increasing-triplet-subsequence.cpp) [Python](./Python/increasing-triplet-subsequence.py) | _O(n)_ | _O(1)_ | Medium ||| 370| [Range Addition](https://leetcode.com/problems/range-addition/) | [C++](./C++/range-addition.cpp) [Python](./Python/range-addition.py) | _O(k + n)_ | _O(1)_ | Medium |馃摉|| 384| [Shuffle an Array](https://leetcode.com/problems/shuffle-an-array/) | [C++](./C++/shuffle-an-array.cpp) [Python](./Python/shuffle-an-array.py) | _O(n)_ | _O(n)_ | Medium | EPI || 396| [Rotate Function](https://leetcode.com/problems/rotate-function/) | [C++](./C++/rotate-function.cpp) [Python](./Python/rotate-function.py) | _O(n)_ | _O(1)_ | Easy ||| 412| [Fizz Buzz](https://leetcode.com/problems/fizz-buzz/) | [C++](./C++/fizz-buzz.cpp) [Python](./Python/fizz-buzz.py) | _O(n)_ | _O(1)_ | Easy ||| 414| [Third Maximum Number](https://leetcode.com/problems/third-maximum-number/) | [C++](./C++/third-maximum-number.cpp) [Python](./Python/third-maximum-number.py) | _O(n)_ | _O(1)_ | Easy ||| 419| [Battleships in a Board](https://leetcode.com/problems/battleships-in-a-board/) | [C++](./C++/battleships-in-a-board.cpp) [Python](./Python/battleships-in-a-board.py) | _O(m * n)_ | _O(1)_ | Medium ||| 422| [Valid Word Square](https://leetcode.com/problems/valid-word-square/) | [C++](./C++/valid-word-square.cpp) [Python](./Python/valid-word-square.py) | _O(m * n)_ | _O(1)_ | Easy |馃摉|| 442| [Find All Duplicates in an Array](https://leetcode.com/problems/find-all-duplicates-in-an-array/) | [C++](./C++/find-all-duplicates-in-an-array.cpp) [Python](./Python/find-all-duplicates-in-an-array.py) | _O(n)_ | _O(1)_ | Medium ||| 448| [Find All Numbers Disappeared in an Array](https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/) | [C++](./C++/find-all-numbers-disappeared-in-an-array.cpp) [Python](./Python/find-all-numbers-disappeared-in-an-array.py) | _O(n)_ | _O(1)_ | Easy ||| ## String | # | Title | Solution | Time | Space | Difficulty | Tag | Note| |-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------|-----| 5| [Longest Palindromic Substring](https://leetcode.com/problems/longest-palindromic-substring/) | [C++](./C++/longest-palindromic-substring.cpp) [Python](./Python/longest-palindromic-substring.py) | _O(n)_ | _O(n)_ | Medium || `Manacher's Algorithm` 6| [ZigZag Conversion](https://leetcode.com/problems/zigzag-conversion/) | [C++](./C++/zigzag-conversion.cpp) [Python](./Python/zigzag-conversion.py) | _O(n)_ | _O(1)_ | Easy || 8| [String to Integer (atoi)](https://leetcode.com/problems/string-to-integer-atoi/) | [C++](./C++/string-to-integer-atoi.cpp) [Python](./Python/string-to-integer-atoi.py) | _O(n)_ | _O(1)_ | Easy || 14| [Longest Common Prefix](https://leetcode.com/problems/longest-common-prefix/) | [C++](./C++/longest-common-prefix.cpp) [Python](./Python/longest-common-prefix.py) | _O(n * k)_ | _O(1)_ | Easy || 28| [Implement strStr()](https://leetcode.com/problems/implement-strstr/) | [C++](./C++/implement-strstr.cpp) [Python](./Python/implement-strstr.py) | _O(n + k)_ | _O(k)_ | Easy || `KMP Algorithm` 38| [Count and Say](https://leetcode.com/problems/count-and-say/) | [C++](./C++/count-and-say.cpp) [Python](./Python/count-and-say.py)| _O(n * 2^n)_ | _O(2^n)_ | Easy || 43| [Multiply Strings](https://leetcode.com/problems/multiply-strings/) | [C++](./C++/multiply-strings.cpp) [Python](./Python/multiply-strings.py) | _O(m * n)_ | _O(m + n)_ | Medium || 58| [Length of Last Word](https://leetcode.com/problems/length-of-last-word/) | [C++](./C++/length-of-last-word.cpp) [Python](./Python/length-of-last-word.py) | _O(n)_ | _O(1)_ | Easy || 67| [Add Binary](https://leetcode.com/problems/add-binary/) | [C++](./C++/add-binary.cpp) [Python](./Python/add-binary.py) | _O(n)_ | _O(1)_ | Easy || 68| [Text Justification](https://leetcode.com/problems/text-justification/) | [C++](./C++/text-justification.cpp) [Python](./Python/text-justification.py) | _O(n)_ | _O(1)_ | Hard || 125| [Valid Palindrome](https://leetcode.com/problems/valid-palindrome/) | [C++](./C++/valid-palindrome.cpp) [Python](./Python/valid-palindrome.py) | _O(n)_ | _O(1)_ | Easy || 151| [Reverse Words in a String](https://leetcode.com/problems/reverse-words-in-a-string/) | [C++](./C++/reverse-words-in-a-string.cpp) [Python](./Python/reverse-words-in-a-string.py) | _O(n)_ | _O(1)_ | Medium || 161| [One Edit Distance](https://leetcode.com/problems/one-edit-distance/) | [C++](./C++/one-edit-distance.cpp) [Python](./Python/one-edit-distance.py) | _O(m + n)_ | _O(1)_ | Medium |馃摉 | 165| [Compare Version Numbers](https://leetcode.com/problems/compare-version-numbers/) | [C++](./C++/compare-version-numbers.cpp) [Python](./Python/compare-version-numbers.py) | _O(n)_ | _O(1)_ | Easy || 186| [Reverse Words in a String II](https://leetcode.com/problems/reverse-words-in-a-string-ii/) |[C++](./C++/reverse-words-in-a-string-ii.cpp) [Python](./Python/reverse-words-in-a-string-ii.py) | _O(n)_ | _O(1)_ | Medium | 馃摉 | 214| [Shortest Palindrome](https://leetcode.com/problems/shortest-palindrome/) | [C++](./C++/shortest-palindrome.cpp) [Python](./Python/shortest-palindrome.py) | _O(n)_ | _O(n)_ | Hard || `KMP Algorithm` `Manacher's Algorithm` 242| [Valid Anagram](https://leetcode.com/problems/valid-anagram/)| [C++](./C++/valid-anagram.cpp) [Python](./Python/valid-anagram.py) | _O(n)_ | _O(1)_ | Easy | LintCode | 271| [Encode and Decode Strings](https://leetcode.com/problems/encode-and-decode-strings/) | [C++](./C++/encode-and-decode-strings.cpp) [Python](./Python/encode-and-decode-strings.py) | _O(n)_ | _O(1)_ | Medium | 馃摉 | 273| [Integer to English Words](https://leetcode.com/problems/integer-to-english-words/) | [C++](./C++/integer-to-english-words.cpp) [Python](./Python/integer-to-english-words.py) | _O(logn)_ | _O(1)_ | Hard | | 306| [Addictive Number](https://leetcode.com/problems/additive-number/) | [C++](./C++/additive-number.cpp) [Python](./Python/additive-number.py) | _O(n^3)_ | _O(n)_ | Medium | | 383| [Ransom Note](https://leetcode.com/problems/ransom-note/) | [C++](./C++/ransom-note.cpp) [Python](./Python/ransom-note.py) | _O(n)_ | _O(1)_ | Easy | EPI | 405| [Convert a Number to Hexadecimal](https://leetcode.com/problems/convert-a-number-to-hexadecimal/) | [C++](./C++/convert-a-number-to-hexadecimal.cpp) [Python](./Python/convert-a-number-to-hexadecimal.py) | _O(n)_ | _O(1)_ | Easy | | 408| [Valid Word Abbreviation](https://leetcode.com/problems/valid-word-abbreviation/) | [C++](./C++/valid-word-abbreviation.cpp) [Python](./Python/valid-word-abbreviation.py) | _O(n)_ | _O(1)_ | Easy | 馃摉 | 415| [Add Strings](https://leetcode.com/problems/add-strings/) | [C++](./C++/add-strings.cpp) [Python](./Python/add-strings.py) | _O(n)_ | _O(1)_ | Easy | | 420| [Strong Password Checker](https://leetcode.com/problems/strong-password-checker/) | [C++](./C++/strong-password-checker.cpp) [Python](./Python/strong-password-checker.py) | _O(n)_ | _O(1)_ | Hard | | 434| [Number of Segments in a String](https://leetcode.com/problems/number-of-segments-in-a-string/) | [C++](./C++/number-of-segments-in-a-string.cpp) [Python](./Python/number-of-segments-in-a-string.py) | _O(n)_ | _O(1)_ | Easy | | 459| [Repeated Substring Pattern](https://leetcode.com/problems/repeated-substring-pattern/) | [C++](./C++/repeated-substring-pattern.cpp) [Python](./Python/repeated-substring-pattern.py) | _O(n)_ | _O(n)_ | Easy || `KMP Algorithm` | 468| [Validate IP Address](https://leetcode.com/problems/validate-ip-address/) | [C++](./C++/validate-ip-address.cpp) [Python](./Python/validate-ip-address.py) | _O(1)_ | _O(1)_ | Medium | | ## Linked List | # | Title | Solution | Time | Space | Difficulty | Tag | Note| |-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------|-----| 2| [Add Two Numbers](https://leetcode.com/problems/add-two-numbers/) | [C++](./C++/add-two-numbers.cpp) [Python](./Python/add-two-numbers.py) | _O(n)_ | _O(1)_ | Medium || 21| [Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/)| [C++](./C++/merge-two-sorted-lists.cpp) [Python](./Python/merge-two-sorted-lists.py) | _O(n)_ | _O(1)_ | Easy || 23| [Merge k Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/) | [C++](./C++/merge-k-sorted-lists.cpp) [Python](./Python/merge-k-sorted-lists.py) | _O(nlogk)_| _O(1)_| Hard | | Heap, Divide and Conquer 24| [Swap Nodes in Pairs](https://leetcode.com/problems/swap-nodes-in-pairs/)| [C++](./C++/swap-nodes-in-pairs.cpp) [Python](./Python/swap-nodes-in-pairs.py) | _O(n)_ | _O(1)_ | Easy || 25| [Reverse Nodes in k-Group](https://leetcode.com/problems/reverse-nodes-in-k-group/)| [C++](./C++/reverse-nodes-in-k-group.cpp) [Python](./Python/reverse-nodes-in-k-group.py) | _O(n)_ | _O(1)_ | Hard || 61| [Rotate List](https://leetcode.com/problems/rotate-list/)| [C++](./C++/rotate-list.cpp) [Python](./Python/rotate-list.py) | _O(n)_ | _O(1)_ | Medium || 82| [Remove Duplicates from Sorted List II](https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/)| [C++](./C++/remove-duplicates-from-sorted-list-ii.cpp) [Python](./Python/remove-duplicates-from-sorted-list-ii.py) | _O(n)_ | _O(1)_ | Medium || 83| [Remove Duplicates from Sorted List](https://leetcode.com/problems/remove-duplicates-from-sorted-list/)| [C++](./C++/remove-duplicates-from-sorted-list.cpp) [Python](./Python/remove-duplicates-from-sorted-list.py) | _O(n)_ | _O(1)_ | Easy || 92| [Reverse Linked List II](https://leetcode.com/problems/reverse-linked-list-ii/)| [C++](./C++/reverse-linked-list-ii.cpp) [Python](./Python/reverse-linked-list-ii.py) | _O(n)_ | _O(1)_ | Medium || 138| [Copy List with Random Pointer](https://leetcode.com/problems/copy-list-with-random-pointer/) | [C++](./C++/copy-list-with-random-pointer.cpp) [Python](./Python/copy-list-with-random-pointer.py) | _O(n)_ | _O(1)_ | Hard || 160| [Intersection of Two Linked Lists](https://leetcode.com/problems/intersection-of-two-linked-lists/)| [C++](./C++/intersection-of-two-linked-lists.cpp) [Python](./Python/intersection-of-two-linked-lists.py) | _O(m + n)_ | _O(1)_ | Easy || 203| [Remove Linked List Elements](https://leetcode.com/problems/remove-linked-list-elements/)| [C++](./C++/remove-linked-list-elements.cpp) [Python](./Python/remove-linked-list-elements.py) | _O(n)_ | _O(1)_ | Easy || 206| [Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/)| [C++](./C++/reverse-linked-list.cpp) [Python](./Python/reverse-linked-list.py) | _O(n)_ | _O(1)_ | Easy || 234| [Palindrome Linked List](https://leetcode.com/problems/palindrome-linked-list/)| [C++](./C++/palindrome-linked-list.cpp) [Python](./Python/palindrome-linked-list.py) | _O(n)_ | _O(1)_ | Easy || 237| [Delete Node in a Linked List](https://leetcode.com/problems/delete-node-in-a-linked-list/)| [C++](./C++/delete-node-in-a-linked-list.cpp) [Python](./Python/delete-node-in-a-linked-list.py) | _O(1)_ | _O(1)_ | Easy | LintCode | 328| [Odd Even Linked List](https://leetcode.com/problems/odd-even-linked-list/)| [C++](./C++/odd-even-linked-list.cpp) [Python](./Python/odd-even-linked-list.py) | _O(n)_ | _O(1)_ | Medium | | 369| [Plus One Linked List](https://leetcode.com/problems/plus-one-linked-list/)| [C++](./C++/plus-one-linked-list.cpp) [Python](./Python/plus-one-linked-list.py) | _O(n)_ | _O(1)_ | Medium | 馃摉 | Two Pointers | 445| [Add Two Numbers II](https://leetcode.com/problems/add-two-numbers-ii/)| [C++](./C++/add-two-numbers-ii.cpp) [Python](./Python/add-two-numbers-ii.py) | _O(m + n)_ | _O(m + n)_ | Medium ||| ## Stack | # | Title | Solution | Time | Space | Difficulty | Tag | Note| |-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------|-----| 20| [Valid Parentheses](https://leetcode.com/problems/valid-parentheses/)| [C++](./C++/valid-parentheses.cpp) [Python](./Python/valid-parentheses.py) | _O(n)_ | _O(n)_ | Easy || 32| [Longest Valid Parentheses](https://leetcode.com/problems/longest-valid-parentheses/)| [C++](./C++/longest-valid-parentheses.cpp) [Python](./Python/longest-valid-parentheses.py) | _O(n)_ | _O(1)_ | Hard || 71| [Simplify Path](https://leetcode.com/problems/simplify-path/)| [C++](./C++/simplify-path.cpp) [Python](./Python/simplify-path.py) | _O(n)_ | _O(n)_ | Medium || 84| [Largest Rectangle in Histogram](https://leetcode.com/problems/largest-rectangle-in-histogram/) | [C++](./C++/largest-rectangle-in-histogram.cpp) [Python](./Python/largest-rectangle-in-histogram.py) | _O(n)_ | _O(n)_ | Hard || Ascending Stack, DP 85| [Maximal Rectangle](https://leetcode.com/problems/maximal-rectangle/)| [C++](./C++/maximal-rectangle.cpp) [Python](./Python/maximal-rectangle.py)| _O(m * n)_ | _O(n)_ | Hard | EPI | Ascending Stack 101| [Symmetric Tree](https://leetcode.com/problems/symmetric-tree/)| [C++](./C++/symmetric-tree.cpp) [Python](./Python/symmetric-tree.py) | _O(n)_ | _O(h)_ | Easy || 150| [Evaluate Reverse Polish Notation](https://leetcode.com/problems/evaluate-reverse-polish-notation/)| [C++](./C++/evaluate-reverse-polish-notation.cpp) [Python](./Python/evaluate-reverse-polish-notation.py)| _O(n)_| _O(n)_| Medium || 155| [Min Stack](https://leetcode.com/problems/min-stack/) | [C++](./C++/min-stack.cpp) [Python](./Python/min-stack.py) | _O(n)_ | _O(1)_ | Easy || 173| [Binary Search Tree Iterator](https://leetcode.com/problems/binary-search-tree-iterator/) | [C++](./C++/binary-search-tree-iterator.cpp) [Python](./Python/binary-search-tree-iterator.py) | _O(1)_| _O(h)_| Medium || 224| [Basic Calculator](https://leetcode.com/problems/basic-calculator/) | [C++](./C++/basic-calculator.cpp) [Python](./Python/basic-calculator.py) | _O(n)_| _O(n)_| Hard || 227| [Basic Calculator II](https://leetcode.com/problems/basic-calculator-ii/) | [C++](./C++/basic-calculator-ii.cpp) [Python](./Python/basic-calculator-ii.py) | _O(n)_| _O(n)_| Medium || 232| [Implement Queue using Stacks](https://leetcode.com/problems/implement-queue-using-stacks/) | [C++](./C++/implement-queue-using-stacks.cpp) [Python](./Python/implement-queue-using-stacks.py) | _O(1), amortized_| _O(n)_| Easy | EPI, LintCode | 255| [Verify Preorder Sequence in Binary Search Tree](https://leetcode.com/problems/verify-preorder-sequence-in-binary-search-tree/) | [C++](./C++/verify-preorder-sequence-in-binary-search-tree.cpp) [Python](./Python/verify-preorder-sequence-in-binary-search-tree.py) | _O(n)_| _O(1)_| Medium |馃摉|| 272| [Closest Binary Search Tree Value II](https://leetcode.com/problems/closest-binary-search-tree-value-ii/) | [C++](./C++/closest-binary-search-tree-value-ii.cpp) [Python](./Python/closest-binary-search-tree-value-ii.py) | _O(h + k)_| _O(h)_| Hard |馃摉|| 331| [Verify Preorder Serialization of a Binary Tree](https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/) | [C++](./C++/verify-preorder-serialization-of-a-binary-tree.cpp) [Python](./Python/verify-preorder-serialization-of-a-binary-tree.py) | _O(n)_| _O(1)_| Medium ||| 341| [Flatten Nested List Iterator](https://leetcode.com/problems/flatten-nested-list-iterator/)| [C++](./C++/flatten-nested-list-iterator.cpp) [Python](./Python/flatten-nested-list-iterator.py) | _O(n)_ | _O(h)_ | Medium |馃摉| Iterator | 385| [Mini Parser](https://leetcode.com/problems/mini-parser/)| [C++](./C++/mini-parser.cpp) [Python](./Python/mini-parser.py) | _O(n)_ | _O(h)_ | Medium ||| 394| [Decode String](https://leetcode.com/problems/decode-string/)| [C++](./C++/decode-string.cpp) [Python](./Python/decode-string.py) | _O(n)_ | _O(h)_ | Medium ||| 439| [Ternary Expression Parser](https://leetcode.com/problems/ternary-expression-parser/) | [C++](./C++/ternary-expression-parser.cpp) [Python](./Python/ternary-expression-parser.py) | _O(n)_ | _O(1)_ | Medium |馃摉| 456| [132 Pattern](https://leetcode.com/problems/132-pattern/) | [C++](./C++/132-pattern.cpp) [Python](./Python/132-pattern.py) | _O(n)_ | _O(n)_ | Medium || ## Queue | # | Title | Solution | Time | Space | Difficulty | Tag | Note| |-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------|-----| 239| [Sliding Window Maximum](https://leetcode.com/problems/sliding-window-maximum/)| [C++](./C++/sliding-window-maximum.cpp) [Python](./Python/sliding-window-maximum.py) | _O(n)_ | _O(k)_ | Hard | EPI, LintCode | 281| [Zigzag Iterator](https://leetcode.com/problems/zigzag-iterator/)| [C++](./C++/zigzag-iterator.cpp) [Python](./Python/zigzag-iterator.py) | _O(n)_ | _O(k)_ | Medium |馃摉|| 346| [Moving Average from Data Stream](https://leetcode.com/problems/moving-average-from-data-stream/)| [C++](./C++/moving-average-from-data-stream.cpp) [Python](./Python/moving-average-from-data-stream.py) | _O(1)_ | _O(w)_ | Easy |馃摉|| ## Heap | # | Title | Solution | Time | Space | Difficulty | Tag | Note| |-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------|-----| 264| [Ugly Number II](https://leetcode.com/problems/ugly-number-ii/) | [C++](./C++/ugly-number-ii.cpp) [Python](./Python/ugly-number-ii.py) | _O(n)_ | _O(1)_ | Medium | CTCI, LintCode | BST, Heap | 295| [Find Median from Data Stream](https://leetcode.com/problems/find-median-from-data-stream/) | [C++](./C++/find-median-from-data-stream.cpp) [Python](./Python/find-median-from-data-stream.py) | _O(nlogn)_ | _O(n)_ | Hard | EPI, LintCode | BST, Heap | 313| [Super Ugly Number](https://leetcode.com/problems/super-ugly-number/) | [C++](./C++/super-ugly-number.cpp) [Python](./Python/super-ugly-number.py) | _O(n * k)_ | _O(n + k)_ | Medium || BST, Heap | 358| [Rearrange String k Distance Apart](https://leetcode.com/problems/rearrange-string-k-distance-apart/)| [C++](./C++/rearrange-string-k-distance-apart.cpp) [Python](./Python/rearrange-string-k-distance-apart.py) | _O(n)_ | _O(n)_ | Hard |馃摉| Greedy, Heap | 373 | [Find K Pairs with Smallest Sums](https://leetcode.com/problems/find-k-pairs-with-smallest-sums/) | [C++](./C++/find-k-pairs-with-smallest-sums.cpp) [Python](./Python/find-k-pairs-with-smallest-sums.py) | _O(k * log(min(n, m, k)))_ | _O(min(n, m, k))_ | Medium ||| 378 | [Kth Smallest Element in a Sorted Matrix](https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/) | [C++](./C++/kth-smallest-element-in-a-sorted-matrix.cpp) [Python](./Python/kth-smallest-element-in-a-sorted-matrix.py) | _O(k * log(min(n, m, k)))_ | _O(min(n, m, k))_ | Medium | LintCode || 407 | [Trapping Rain Water II](https://leetcode.com/problems/trapping-rain-water-ii/) | [C++](./C++/trapping-rain-water-ii.cpp) [Python](./Python/trapping-rain-water-ii.py) | _O(m * n * (logm + logn))_ | _O(m * n)_ | Hard | LintCode || ## Tree | # | Title | Solution | Time | Space | Difficulty | Tag | Note| |-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------|-----| 94 | [Binary Tree Inorder Traversal](https://leetcode.com/problems/binary-tree-inorder-traversal/) | [C++](./C++/binary-tree-inorder-traversal.cpp) [Python](./Python/binary-tree-inorder-traversal.py) | _O(n)_| _O(1)_| Medium || `Morris Traversal` | 99 | [Recover Binary Search Tree](https://leetcode.com/problems/recover-binary-search-tree/) | [C++](./C++/recover-binary-search-tree.cpp) [Python](./Python/recover-binary-search-tree.py) | _O(n)_| _O(1)_| Hard || `Morris Traversal` 144 | [Binary Tree Preorder Traversal](https://leetcode.com/problems/binary-tree-preorder-traversal/) | [C++](./C++/binary-tree-preorder-traversal.cpp) [Python](./Python/binary-tree-preorder-traversal.py) | _O(n)_| _O(1)_| Medium || `Morris Traversal` 145 | [Binary Tree Postorder Traversal](https://leetcode.com/problems/binary-tree-postorder-traversal/) | [C++](./C++/binary-tree-postorder-traversal.cpp) [Python](./Python/binary-tree-postorder-traversal.py) | _O(n)_| _O(1)_| Hard || `Morris Traversal` 208 | [Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree/) | [C++](./C++/implement-trie-prefix-tree.cpp) [Python](./Python/implement-trie-prefix-tree.py) | _O(n)_ | _O(1)_ | Medium || Trie 211 | [Add and Search Word - Data structure design](https://leetcode.com/problems/add-and-search-word-data-structure-design/) | [C++](./C++/add-and-search-word-data-structure-design.cpp) [Python](./Python/add-and-search-word-data-structure-design.py) | _O(min(n, h))_ | _O(min(n, h))_ | Medium || Trie, DFS 226| [Invert Binary Tree](https://leetcode.com/problems/invert-binary-tree/) | [C++](./C++/invert-binary-tree.cpp) [Python](./Python/invert-binary-tree.py) | _O(n)_ | _O(h)_, _O(w)_ | Easy || 297 | [Serialize and Deserialize Binary Tree](https://leetcode.com/problems/serialize-and-deserialize-binary-tree/) | [C++](./C++/serialize-and-deserialize-binary-tree.cpp) [Python](./Python/serialize-and-deserialize-binary-tree.py) | _O(n)_ | _O(h)_ | Hard | LintCode | DFS 307 | [Range Sum Query - Mutable](https://leetcode.com/problems/range-sum-query-mutable/) | [C++](./C++/range-sum-query-mutable.cpp) [Python](./Python/range-sum-query-mutable.py) | ctor: _O(n)_, update: _O(logn)_, query: _O(logn)_ | _O(n)_ | Medium | LintCode | DFS, Segment Tree, BIT 308 | [Range Sum Query 2D - Mutable](https://leetcode.com/problems/range-sum-query-2d-mutable/) | [C++](./C++/range-sum-query-2d-mutable.cpp) [Python](./Python/range-sum-query-2d-mutable.py) | ctor: _O(m * n)_, update: _O(logm + logn)_, query: _O(logm + logn)_ | _O(m * n)_ | Hard | 馃摉 | DFS, Segment Tree, BIT 315|[Count of Smaller Numbers After Self](https://leetcode.com/problems/count-of-smaller-numbers-after-self/)| [C++](./C++/count-of-smaller-numbers-after-self.cpp) [Python](./Python/count-of-smaller-numbers-after-self.py)| _O(nlogn)_ | _O(n)_ | Hard | LintCode | BST, BIT, Divide and Conquer | ## Hash Table | # | Title | Solution | Time | Space | Difficulty | Tag | Note| |-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------|-----| 1| [Two Sum](https://leetcode.com/problems/two-sum/) | [C++](./C++/two-sum.cpp) [Python](./Python/two-sum.py) | _O(n)_ | _O(n)_ | Easy || 3| [Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/) | [C++](./C++/longest-substring-without-repeating-characters.cpp) [Python](./Python/longest-substring-without-repeating-characters.py) | _O(n)_ | _O(1)_ | Medium || 30| [Substring with Concatenation of All Words](https://leetcode.com/problems/substring-with-concatenation-of-all-words/) | [C++](./C++/substring-with-concatenation-of-all-words.cpp) [Python](./Python/substring-with-concatenation-of-all-words.py) | _O(m * n * k)_ | _O(n * k)_ | Hard || 36| [Valid Sudoku](https://leetcode.com/problems/valid-sudoku/) | [C++](./C++/valid-sudoku.cpp) [Python](./Python/valid-sudoku.py) | _O(9^2)_ | _O(9)_ | Easy || 49| [Group Anagrams](https://leetcode.com/problems/anagrams/) | [C++](./C++/anagrams.cpp) [Python](./Python/anagrams.py) | _O(n * glogg)_ | _O(n)_ | Medium || 76| [Minimum Window Substring](https://leetcode.com/problems/minimum-window-substring/) | [C++](./C++/minimum-window-substring.cpp) [Python](./Python/minimum-window-substring.py) | _O(n)_ | _O(k)_ | Hard || 149| [Max Points on a Line](https://leetcode.com/problems/max-points-on-a-line/) | [C++](./C++/max-points-on-a-line.cpp) [Python](./Python/max-points-on-a-line.py) | _O(n^2)_ | _O(n)_ | Hard || 159| [Longest Substring with At Most Two Distinct Characters](https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/)| [C++](./C++/longest-substring-with-at-most-two-distinct-characters.cpp) [Python](./Python/longest-substring-with-at-most-two-distinct-characters.py) | _O(n)_ | _O(1)_ | Hard |馃摉| 170| [Two Sum III - Data structure design](https://leetcode.com/problems/two-sum-iii-data-structure-design/) | [C++](./C++/two-sum-iii-data-structure-design.cpp) [Python](./Python/two-sum-iii-data-structure-design.py) | _O(n)_ | _O(n)_ | Easy | 馃摉 | 187| [Repeated DNA Sequences](https://leetcode.com/problems/repeated-dna-sequences/) | [Python](./Python/repeated-dna-sequences.py) | _O(n)_ | _O(n)_ | Medium || 202| [Happy Number](https://leetcode.com/problems/happy-number/) | [C++](./C++/happy-number.cpp) [Python](./Python/happy-number.py) | _O(k)_ | _O(k)_ | Easy || 204| [Count Primes](https://leetcode.com/problems/count-primes/) | [C++](./C++/count-primes.cpp) [Python](./Python/count-primes.py) | _O(n)_ | _O(n)_ | Easy || 205| [Isomorphic Strings](https://leetcode.com/problems/isomorphic-strings/) | [C++](./C++/isomorphic-strings.cpp) [Python](./Python/isomorphic-strings.py) | _O(n)_ | _O(1)_ | Easy || 217| [Contains Duplicate](https://leetcode.com/problems/contains-duplicate/) | [C++](./C++/contains-duplicate.cpp) [Python](./Python/contains-duplicate.py) | _O(n)_ | _O(n)_ | Easy || 219| [Contains Duplicate II](https://leetcode.com/problems/contains-duplicate-ii/) | [C++](./C++/contains-duplicate-ii.cpp) [Python](./Python/contains-duplicate-ii.py) | _O(n)_ | _O(n)_ | Easy || 244| [Shortest Word Distance II](https://leetcode.com/problems/shortest-word-distance-ii/) | [C++](./C++/shortest-word-distance-ii.cpp) [Python](./Python/shortest-word-distance-ii.py) | ctor: _O(n)_, lookup: _O(a + b)_ | _O(n)_ | Medium |馃摉|| 246| [Strobogrammatic Number](https://leetcode.com/problems/strobogrammatic-number/) | [C++](./C++/strobogrammatic-number.cpp) [Python](./Python/strobogrammatic-number.py) | _O(n)_ | _O(1)_ | Easy |馃摉|| 249| [Group Shifted Strings](https://leetcode.com/problems/group-shifted-strings/) | [C++](./C++/group-shifted-strings.cpp) [Python](./Python/group-shifted-strings.py) | _O(nlogn)_ | _O(n)_ | Easy |馃摉|| 266| [Palindrome Permutation](https://leetcode.com/problems/palindrome-permutation/) | [C++](./C++/palindrome-permutation.cpp) [Python](./Python/palindrome-permutation.py) | _O(n)_ | _O(1)_ | Easy |馃摉|| 288| [Unique Word Abbreviation](https://leetcode.com/problems/unique-word-abbreviation/) | [C++](./C++/unique-word-abbreviation.cpp) [Python](./Python/unique-word-abbreviation.py) | ctor: _O(n)_, lookup: _O(1)_ | _O(k)_ | Easy |馃摉|| 290| [Word Pattern](https://leetcode.com/problems/word-pattern/) | [C++](./C++/word-pattern.cpp) [Python](./Python/word-pattern.py) | _O(n)_ | _O(c)_ | Easy | variant of [Isomorphic Strings](https://leetcode.com/problems/isomorphic-strings/) || 299| [Bulls and Cows](https://leetcode.com/problems/bulls-and-cows/) | [C++](./C++/bulls-and-cows.cpp) [Python](./Python/bulls-and-cows.py) | _O(n)_ | _O(1)_ | Easy ||| 305| [Number of Islands II](https://leetcode.com/problems/number-of-islands-ii/) | [C++](./C++/number-of-islands-ii.cpp) [Python](./Python/number-of-islands-ii.py) | _O(k)_ | _O(k)_| Hard | LintCode, 馃摉 | Union Find 314| [Binary Tree Vertical Order Traversal](https://leetcode.com/problems/binary-tree-vertical-order-traversal/) | [C++](./C++/binary-tree-vertical-order-traversal.cpp) [Python](./Python/binary-tree-vertical-order-traversal.py) | _O(n)_ | _O(n)_| Medium | 馃摉 | BFS 323| [Number of Connected Components in an Undirected Graph](https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/) | [C++](./C++/number-of-connected-components-in-an-undirected-graph.cpp) [Python](./Python/number-of-connected-components-in-an-undirected-graph.py) | _O(n)_ | _O(n)_| Medium | 馃摉 | Union Find 325| [Maximum Size Subarray Sum Equals k](https://leetcode.com/problems/maximum-size-subarray-sum-equals-k/) | [C++](./C++/maximum-size-subarray-sum-equals-k.cpp) [Python](./Python/maximum-size-subarray-sum-equals-k.py) | _O(n)_ | _O(n)_| Medium | 馃摉 | 336| [Palindrome Pairs](https://leetcode.com/problems/palindrome-pairs/) | [C++](./C++/palindrome-pairs.cpp) [Python](./Python/palindrome-pairs.py) | _O(n * k^2)_ | _O(n * k)_ | Hard | | | 340| [Longest Substring with At Most K Distinct Characters](https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/)| [C++](./C++/longest-substring-with-at-most-k-distinct-characters.cpp) [Python](./Python/longest-substring-with-at-most-k-distinct-characters.py) | _O(n)_ | _O(1)_ | Hard |馃摉| 356| [Line Reflection](https://leetcode.com/problems/line-reflection/) | [C++](./C++/line-reflection.cpp) [Python](./Python/line-reflection.py) | _O(n)_| _O(n)_| Medium |馃摉| Hash, Two Pointers | 387| [First Unique Character in a String](https://leetcode.com/problems/first-unique-character-in-a-string/) | [C++](./C++/first-unique-character-in-a-string.cpp) [Python](./Python/first-unique-character-in-a-string.py) | _O(n)_| _O(n)_| Easy ||| 388| [Longest Absolute File Path](https://leetcode.com/problems/longest-absolute-file-path/) | [C++](./C++/longest-absolute-file-path.cpp) [Python](./Python/longest-absolute-file-path.py) | _O(n)_| _O(d)_| Medium || Stack | 409| [Longest Palindrome](https://leetcode.com/problems/longest-palindrome/) | [C++](./C++/longest-palindrome.cpp) [Python](./Python/longest-palindrome.py) | _O(n)_| _O(1)_| Easy ||| 424| [Longest Repeating Character Replacement](https://leetcode.com/problems/longest-repeating-character-replacement/) | [C++](./C++/longest-repeating-character-replacement.cpp) [Python](./Python/longest-repeating-character-replacement.py) | _O(n)_| _O(1)_| Medium ||| 438| [Find All Anagrams in a String](https://leetcode.com/problems/find-all-anagrams-in-a-string/) | [C++](./C++/find-all-anagrams-in-a-string.cpp) [Python](./Python/find-all-anagrams-in-a-string.py) | _O(n)_ | _O(1)_ | Easy || 447| [Number of Boomerangs](https://leetcode.com/problems/number-of-boomerangs/) | [C++](./C++/number-of-boomerangs.cpp) [Python](./Python/number-of-boomerangs.py) | _O(n^2)_ | _O(n)_ | Easy || 454| [4Sum II](https://leetcode.com/problems/4sum-ii/) | [C++](./C++/4sum-ii.cpp) [Python](./Python/4sum-ii.py) | _O(n^2)_ | _O(n^2)_ | Medium || 473| [Matchsticks to Square](https://leetcode.com/problems/matchsticks-to-square/) | [C++](./C++/matchsticks-to-square.cpp) [Python](./Python/matchsticks-to-square.py) | _O(n * s * 2^n)_ | _O(n * (2^n + s))_ | Medium || ## Data Structure | # | Title | Solution | Time | Space | Difficulty | Tag | Note| |-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------|-----| 146| [LRU Cache](https://leetcode.com/problems/lru-cache/) | [C++](./C++/lru-cache.cpp) [Python](./Python/lru-cache.py) | _O(1)_ | _O(k)_ | Hard || 225| [Implement Stack using Queues](https://leetcode.com/problems/implement-stack-using-queues/) | [C++](./C++/implement-stack-using-queues.cpp) [Python](./Python/implement-stack-using-queues.py) | push: _O(n)_, pop: _O(1)_, top: _O(1)_ | _O(n)_ | Easy || ## Math | # | Title | Solution | Time | Space | Difficulty | Tag | Note| |-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------|-----| 7| [Reverse Integer](https://leetcode.com/problems/reverse-integer/) | [C++](./C++/reverse-integer.cpp) [Python](./Python/reverse-integer.py) | _O(1)_ | _O(1)_ | Easy || 9| [Palindrome Number](https://leetcode.com/problems/palindrome-number/) | [C++](./C++/palindrome-number.cpp) [Python](./Python/palindrome-number.py) | _O(1)_ | _O(1)_ | Easy || 12| [Integer to Roman](https://leetcode.com/problems/integer-to-roman/) | [C++](./C++/integer-to-roman.cpp) [Python](./Python/integer-to-roman.py) | _O(n)_ | _O(1)_ | Medium || 13| [Roman to Integer](https://leetcode.com/problems/roman-to-integer/) | [C++](./C++/roman-to-integer.cpp) [Python](./Python/roman-to-integer.py) | _O(n)_ | _O(1)_ | Easy || 29| [Divide Two Integers](https://leetcode.com/problems/divide-two-integers/) | [C++](./C++/divide-two-integers.cpp) [Python](./Python/divide-two-integers.py) | _O(1)_ | _O(1)_ | Medium || 50| [Pow(x, n)](https://leetcode.com/problems/powx-n/) | [C++](./C++/powx-n.cpp) [Python](./Python/powx-n.py) | _O(1)_ | _O(1)_ | Medium || 60| [Permutation Sequence](https://leetcode.com/problems/permutation-sequence/) | [C++](./C++/permutation-sequence.cpp) [Python](./Python/permutation-sequence.py) | _O(n^2)_ | _O(n)_ | Medium || `Cantor Ordering` 65| [Valid Number](https://leetcode.com/problems/valid-number/) | [C++](./C++/valid-number.cpp) [Python](./Python/valid-number.py) | _O(n)_ | _O(1)_ | Hard || `Automata` 89| [Gray Code](https://leetcode.com/problems/gray-code/) | [C++](./C++/gray-code.cpp) [Python](./Python/gray-code.py) | _O(2^n)_ | _O(1)_ | Medium || 166| [Fraction to Recurring Decimal](https://leetcode.com/problems/fraction-to-recurring-decimal/) | [C++](./C++/fraction-to-recurring-decimal.cpp) [Python](./Python/fraction-to-recurring-decimal.py) | _O(logn)_ | _O(1)_ | Medium || 168| [Excel Sheet Column Title](https://leetcode.com/problems/excel-sheet-column-title/) | [C++](./C++/excel-sheet-column-title.cpp) [Python](./Python/excel-sheet-column-title.py) | _O(logn)_ | _O(1)_ | Easy || 171| [Excel Sheet Column Number](https://leetcode.com/problems/excel-sheet-column-number/) | [C++](./C++/excel-sheet-column-number.cpp) [Python](./Python/excel-sheet-column-number.py) | _O(n)_ | _O(1)_ | Easy || 172| [Factorial Trailing Zeroes](https://leetcode.com/problems/factorial-trailing-zeroes/) | [C++](./C++/factorial-trailing-zeroes.cpp) [Python](./Python/factorial-trailing-zeroes.py) | _O(1)_ | _O(1)_ | Easy || 223| [Rectangle Area](https://leetcode.com/problems/rectangle-area/) | [C++](./C++/rectangle-area.cpp) [Python](./Python/rectangle-area.py) | _O(1)_ | _O(1)_ | Easy || 233| [Number of Digit One](https://leetcode.com/problems/number-of-digit-one/) | [C++](./C++/number-of-digit-one.cpp) [Python](./Python/number-of-digit-one.py) | _O(1)_ | _O(1)_ | Hard | CTCI, LintCode| 248| [Strobogrammatic Number III](https://leetcode.com/problems/strobogrammatic-number-iii/) | [C++](./C++/strobogrammatic-number-iii.cpp) [Python](./Python/strobogrammatic-number-iii.py) | _O(5^(n/2))_ | _O(n)_ | Hard |馃摉|| 258| [Add Digits](https://leetcode.com/problems/add-digits/) | [C++](./C++/add-digits.cpp) [Python](./Python/add-digits.py) | _O(1)_ | _O(1)_ | Easy ||| 263| [Ugly Number](https://leetcode.com/problems/ugly-number/) | [C++](./C++/ugly-number.cpp) [Python](./Python/ugly-number.py) | _O(1)_ | _O(1)_ | Easy ||| 292| [Nim Game](https://leetcode.com/problems/nim-game/) | [C++](./C++/nim-game.cpp) [Python](./Python/nim-game.py) | _O(1)_ | _O(1)_ | Easy | LintCode || 319 | [Bulb Switcher](https://leetcode.com/problems/bulb-switcher/) | [C++](./C++/bulb-switcher.cpp) [Python](./Python/bulb-switcher.py) | _O(1)_ | _O(1)_ | Medium ||| 326 | [Power of Three](https://leetcode.com/problems/power-of-three/) | [C++](./C++/power-of-three.cpp) [Python](./Python/power-of-three.py) | _O(1)_ | _O(1)_ | Easy ||| 335 | [Self Crossing](https://leetcode.com/problems/self-crossing/) | [C++](./C++/self-crossing.cpp) [Python](./Python/self-crossing.py) | _O(n)_ | _O(1)_ | Hard ||| 338 | [Counting Bits](https://leetcode.com/problems/counting-bits/) | [C++](./C++/counting-bits.cpp) [Python](./Python/counting-bits.py) | _O(n)_ | _O(n)_ | Medium ||| 343 | [Integer Break](https://leetcode.com/problems/integer-break/) | [C++](./C++/integer-break.cpp) [Python](./Python/integer-break.py) | _O(logn)_ | _O(1)_ | Medium || Tricky, DP | 365 | [Water and Jug Problem](https://leetcode.com/problems/water-and-jug-problem/) | [C++](./C++/water-and-jug-problem.cpp) [Python](./Python/water-and-jug-problem.py) | _O(logn)_ | _O(1)_ | Medium || Euclidean Algorithm | 372 | [Super Pow](https://leetcode.com/problems/super-pow/) | [C++](./C++/super-pow.cpp) [Python](./Python/super-pow.py) | _O(n)_ | _O(1)_ | Medium ||| 382 | [Linked List Random Node](https://leetcode.com/problems/linked-list-random-node/) | [C++](./C++/linked-list-random-node.cpp) [Python](./Python/linked-list-random-node.py) | _O(n)_ | _O(1)_ | Medium || `Reservoir Sampling` | 386 | [Lexicographical Numbers](https://leetcode.com/problems/lexicographical-numbers/) | [C++](./C++/lexicographical-numbers.cpp) [Python](./Python/lexicographical-numbers.py) | _O(n)_ | _O(1)_ | Medium ||| 390 | [Elimination Game](https://leetcode.com/problems/elimination-game/) | [C++](./C++/elimination-game.cpp) [Python](./Python/elimination-game.py) | _O(logn)_ | _O(1)_ | Medium || 391 | [Perfect Rectangle](https://leetcode.com/problems/perfect-rectangle/) | [C++](./C++/perfect-rectangle.cpp) [Python](./Python/perfect-rectangle.py) | _O(n)_ | _O(n)_ | Hard | | 398 | [Random Pick Index](https://leetcode.com/problems/random-pick-index/) | [C++](./C++/random-pick-index.cpp) [Python](./Python/random-pick-index.py) | _O(n)_ | _O(1)_ | Medium || `Reservoir Sampling` | 400 | [Nth Digit](https://leetcode.com/problems/nth-digit/) | [C++](./C++/nth-digit.cpp) [Python](./Python/nth-digit.py) | _O(logn)_ | _O(1)_ | Easy ||| 413 | [Arithmetic Slices](https://leetcode.com/problems/arithmetic-slices/) | [C++](./C++/arithmetic-slices.cpp) [Python](./Python/arithmetic-slices.py) | _O(n)_ | _O(1)_ | Medium ||| 423 | [Reconstruct Original Digits from English](https://leetcode.com/problems/reconstruct-original-digits-from-english/) | [C++](./C++/reconstruct-original-digits-from-english.cpp) [Python](./Python/reconstruct-original-digits-from-english.py) | _O(n)_ | _O(1)_ | Medium | [GCJ2016 - Round 1B](https://code.google.com/codejam/contest/11254486/dashboard#s=p0)|| 441 | [Arranging Coins](https://leetcode.com/problems/arranging-coins/) | [C++](./C++/arranging-coins.cpp) [Python](./Python/arranging-coins.py) | _O(nlogn)_ | _O(1)_ | Easy || Binary Search| 453 | [Minimum Moves to Equal Array Elements](https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/) | [C++](./C++/minimum-number-of-arrows-to-burst-balloons.cpp) [Python](./Python/minimum-number-of-arrows-to-burst-balloons.py) | _O(n)_ | _O(1)_ | Easy ||| 458 | [Poor Pigs](https://leetcode.com/problems/poor-pigs/) | [C++](./C++/poor-pigs.cpp) [Python](./Python/poor-pigs.py) | _O(n)_ | _O(1)_ | Easy ||| 469 | [Convex Polygon](https://leetcode.com/problems/convex-polygon/) | [C++](./C++/convex-polygon.cpp) [Python](./Python/convex-polygon.py) | _O(n)_ | _O(1)_ | Medium |馃摉|| ## Sort | # | Title | Solution | Time | Space | Difficulty | Tag | Note| |-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------|-----| 56| [Merge Intervals](https://leetcode.com/problems/merge-intervals/)| [C++](./C++/merge-intervals.cpp) [Python](./Python/merge-intervals.py) | _O(nlogn)_ | _O(1)_ | Hard || 57| [Insert Interval](https://leetcode.com/problems/insert-interval/)| [C++](./C++/insert-interval.cpp) [Python](./Python/insert-interval.py) | _O(n)_ | _O(1)_ | Hard || 75| [Sort Colors](https://leetcode.com/problems/sort-colors/) | [C++](./C++/sort-colors.cpp) [Python](./Python/sort-colors.py) | _O(n)_ | _O(1)_ | Medium || Tri Partition 88| [Merge Sorted Array](https://leetcode.com/problems/merge-sorted-array/)| [C++](./C++/merge-sorted-array.cpp) [Python](./Python/merge-sorted-array.py) | _O(n)_ | _O(1)_ | Easy || 147| [Insertion Sort List](https://leetcode.com/problems/insertion-sort-list/)|[C++](./C++/insertion-sort-list.cpp) [Python](./Python/insertion-sort-list.py) | _O(n^2)_ | _O(1)_ | Medium || 148| [Sort List](https://leetcode.com/problems/sort-list/) | [C++](./C++/sort-list.cpp) [Python](./Python/sort-list.py) | _O(nlogn)_ | _O(logn)_ | Medium || 164| [Maximum Gap](https://leetcode.com/problems/maximum-gap/) | [C++](./C++/maximum-gap.cpp) [Python](./Python/maximum-gap.py)| _O(n)_ | _O(n)_ | Hard || Tricky 179| [Largest Number](https://leetcode.com/problems/largest-number/) | [C++](./C++/largest-number.cpp) [Python](./Python/largest-number.py) | _O(nlogn)_ | _O(1)_ | Medium || 218| [The Skyline Problem](https://leetcode.com/problems/the-skyline-problem/) | [C++](./C++/the-skyline-problem.cpp) [Python](./Python/the-skyline-problem.py) | _O(nlogn)_ | _O(n)_ | Hard || Sort, BST| 252| [Meeting Rooms](https://leetcode.com/problems/meeting-rooms/) | [C++](./C++/meeting-rooms.cpp) [Python](./Python/meeting-rooms.py) | _O(nlogn)_ | _O(n)_ | Easy |馃摉| | 253| [Meeting Rooms II](https://leetcode.com/problems/meeting-rooms-ii/) | [C++](./C++/meeting-rooms-ii.cpp) [Python](./Python/meeting-rooms-ii.py) | _O(nlogn)_ | _O(n)_ | Medium |馃摉| | 274| [H-Index](https://leetcode.com/problems/h-index/) | [C++](./C++/h-index.cpp) [Python](./Python/h-index.py) | _O(n)_ | _O(n)_ | Medium || Counting Sort | 280| [Wiggle Sort](https://leetcode.com/problems/wiggle-sort/) | [C++](./C++/wiggle-sort.cpp) [Python](./Python/wiggle-sort.py) | _O(n)_ | _O(1)_ | Medium |馃摉| | 324| [Wiggle Sort II](https://leetcode.com/problems/wiggle-sort-ii/) | [C++](./C++/wiggle-sort-ii.cpp) [Python](./Python/wiggle-sort-ii.py) | _O(n)_ on average | _O(1)_ | Medium | variant of [Sort Colors](https://leetcode.com/problems/sort-colors/) | Tri Partition | 347| [Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/) | [C++](./C++/top-k-frequent-elements.cpp) [Python](./Python/top-k-frequent-elements.py) | _O(n)_ on average | _O(n)_ | Medium | | Quick Select, Heap | 406| [Queue Reconstruction by Height](https://leetcode.com/problems/queue-reconstruction-by-height/) | [C++](./C++/queue-reconstruction-by-height.cpp) [Python](./Python/queue-reconstruction-by-height.py) | _O(n * sqrt(n))_ | _O(n)_ | Medium | | | 451| [Sort Characters By Frequency](https://leetcode.com/problems/sort-characters-by-frequency/) | [C++](./C++/sort-characters-by-frequency.cpp) [Python](./Python/sort-characters-by-frequency.py) | _O(n)_ | _O(n)_ | Medium | | | ## Two Pointers | # | Title | Solution | Time | Space | Difficulty | Tag | Note| |-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------|-----| 19| [Remove Nth Node From End of List](https://leetcode.com/problems/remove-nth-node-from-end-of-list/)| [C++](./C++/remove-nth-node-from-end-of-list.cpp) [Python](./Python/remove-nth-node-from-end-of-list.py) | _O(n)_ | _O(1)_ | Easy || 86| [Partition List](https://leetcode.com/problems/partition-list/)| [C++](./C++/partition-list.cpp) [Python](./Python/partition-list.py) | _O(n)_ | _O(1)_ | Medium || 141| [Linked List Cycle](https://leetcode.com/problems/linked-list-cycle/)| [C++](./C++/linked-list-cycle.cpp) [Python](./Python/linked-list-cycle.py) | _O(n)_ | _O(1)_ | Easy || 142| [Linked List Cycle II](https://leetcode.com/problems/linked-list-cycle-ii/)| [C++](./C++/linked-list-cycle-ii.cpp) [Python](./Python/linked-list-cycle-ii.py) | _O(n)_ | _O(1)_ | Medium || 143| [Reorder List](https://leetcode.com/problems/reorder-list/)| [C++](./C++/reorder-list.cpp) [Python](./Python/reorder-list.py) | _O(n)_ | _O(1)_ | Medium || 167| [Two Sum II - Input array is sorted](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/) | [C++](./C++/two-sum-ii-input-array-is-sorted.cpp) [Python](./Python/two-sum-ii-input-array-is-sorted.py) | _O(n)_ | _O(1)_ | Medium | | 259 | [3Sum Smaller](https://leetcode.com/problems/3sum-smaller/) | [C++](./C++/3sum-smaller.cpp) [Python](./Python/3sum-smaller.py) | _O(n^2)_ | _O(1)_ | Medium | 馃摉, LintCode | 283 | [Move Zeroes](https://leetcode.com/problems/move-zeroes/) | [C++](./C++/move-zeroes.cpp) [Python](./Python/move-zeroes.py) | _O(n)_ | _O(1)_ | Easy | | 287| [Find the Duplicate Number](https://leetcode.com/problems/find-the-duplicate-number/)| [C++](./C++/find-the-duplicate-number.cpp) [Python](./Python/find-the-duplicate-number.py) | _O(n)_ | _O(1)_ | Hard | | Binary Search, Two Pointers | 344| [Reverse String](https://leetcode.com/problems/reverse-string/) | [C++](./C++/reverse-string.cpp) [Python](./Python/reverse-string.py) | _O(n)_ | _O(1)_ | Easy | | 345| [Reverse Vowels of a String](https://leetcode.com/problems/reverse-vowels-of-a-string/) | [C++](./C++/reverse-vowels-of-a-string.cpp) [Python](./Python/reverse-vowels-of-a-string.py) | _O(n)_ | _O(1)_ | Easy | | 349| [Intersection of Two Arrays](https://leetcode.com/problems/intersection-of-two-arrays/) | [C++](./C++/intersection-of-two-arrays.cpp) [Python](./Python/intersection-of-two-arrays.py) | _O(m + n)_ | _O(min(m, n))_ | Easy | EPI | Hash, Binary Search 350| [Intersection of Two Arrays II](https://leetcode.com/problems/intersection-of-two-arrays-ii/) | [C++](./C++/intersection-of-two-arrays-ii.cpp) [Python](./Python/intersection-of-two-arrays-ii.py) | _O(m + n)_ | _O(1)_ | Easy | EPI | Hash, Binary Search 360| [Sort Transformed Array](https://leetcode.com/problems/sort-transformed-array/) | [C++](./C++/sort-transformed-array.cpp) [Python](./Python/sort-transformed-array.py) | _O(n)_ | _O(1)_ | Medium |馃摉| 457| [Circular Array Loop](https://leetcode.com/problems/circular-array-loop/) | [C++](./C++/circular-array-loop.cpp) [Python](./Python/circular-array-loop.py) | _O(n)_ | _O(1)_ | Medium || ## Recursion | # | Title | Solution | Time | Space | Difficulty | Tag | Note| |-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------|-----| 95| [Unique Binary Search Trees II](https://leetcode.com/problems/unique-binary-search-trees-ii/) | [C++](./C++/unique-binary-search-trees-ii.cpp) [Python](./Python/unique-binary-search-trees-ii.py) | _O(4^n / n^(3/2)_ | _O(4^n / n^(3/2)_ | Medium || 98| [Validate Binary Search Tree](https://leetcode.com/problems/validate-binary-search-tree/)|[C++](./C++/validate-binary-search-tree.cpp) [Python](./Python/validate-binary-search-tree.py)| _O(n)_ | _O(1)_ | Medium || 100| [Same Tree](https://leetcode.com/problems/same-tree/) |[C+](./C++/same-tree.cpp) [Python](./Python/same-tree.py) | _O(n)_ | _O(h)_ | Easy || 104| [Maximum Depth of Binary Tree](https://leetcode.com/problems/maximum-depth-of-binary-tree/)| [C++](./C++/maximum-depth-of-binary-tree.cpp) [Python](./Python/maximum-depth-of-binary-tree.py)| _O(n)_ | _O(h)_ | Easy || 105| [Construct Binary Tree from Preorder and Inorder Traversal](https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/) | [C++](./C++/construct-binary-tree-from-preorder-and-inorder-traversal.cpp) [Python](./Python/construct-binary-tree-from-preorder-and-inorder-traversal.py) | _O(n)_ | _O(n)_ | Medium || 106| [Construct Binary Tree from Inorder and Postorder Traversal](https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/) | [C++](./C++/construct-binary-tree-from-inorder-and-postorder-traversal.cpp) [Python](./Python/construct-binary-tree-from-inorder-and-postorder-traversal.py) | _O(n)_ | _O(n)_ | Medium || 108| [Convert Sorted Array to Binary Search Tree](https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/) | [C++](./C++/convert-sorted-array-to-binary-search-tree.cpp) [Python](./Python/convert-sorted-array-to-binary-search-tree.py) | _O(n)_ | _O(logn)_ | Medium || 109| [Convert Sorted List to Binary Search Tree](https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/) | [C++](./C++/convert-sorted-list-to-binary-search-tree.cpp) [Python](./Python/convert-sorted-list-to-binary-search-tree.py) | _O(n)_ | _O(logn)_ | Medium || 110| [Balanced Binary Tree](https://leetcode.com/problems/balanced-binary-tree/) | [Python](./Python/balanced-binary-tree.py) | _O(n)_| _O(h)_ | Easy || 111| [Minimum Depth of Binary Tr
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值