ZXAlgorithm - Leetcode Top Interview Questions Easy Collection刷题日记

Easy Collections

1 Array

Remove Duplicates from Sorted Array
https://leetcode.com/explore/interview/card/top-interview-questions-easy/92/array/727/
Two pointer
Rotate Array
https://leetcode.com/explore/interview/card/top-interview-questions-easy/92/array/646/
k % len(nums) 三次翻转
Valid Sudoku
https://leetcode.com/problems/valid-sudoku/discuss/15460/1-7-lines-Python-4-solutions
enumerate()
seen += [(i, c), (c, j), (i//3, j//3, c)]
通过把row和column index位置放置在不同的位置,统一比较的逻辑
list comprehension https://blog.csdn.net/zhanh1218/article/details/26590837
Rotate Image
https://leetcode.com/problems/rotate-image/discuss/18884/Seven-Short-Solutions-(1-to-7-lines)
https://stackoverflow.com/questions/509211/understanding-slice-notation
matrix[:] = zip(*(matrix[::-1]))
使用zip和unzip
左向翻转
https://www.runoob.com/python/python-func-map.html

matrix = [[1,2,3],[4,5,6],[7,8,9]]
matrix[:] = map(lambda x: x[::-1], matrix[:])
print(matrix)
matrix[:] = map(list, zip(*(matrix[:])))
print(matrix)

2 String

Reverse Integer
https://leetcode.com/problems/reverse-integer/discuss/4055/Golfing-in-Python
The range of a 32-bit signed integer would be-231 ~ 231-1, which is -2147483648 ~ 2147483647. So if I input -8463847412 (the reverse integer is exactly -2**31, inside the range),because -8463847412 is not a valid 32 bit int

class Solution(object):
    def reverse(self, x):
        s = (x > 0) - (x < 0)
        r = int(str(x*s)[::-1])
        return s*r * (r < 2**31)

First Unique Character in a String
https://leetcode.com/explore/interview/card/top-interview-questions-easy/127/strings/881/
使用python counter类(dict的子类)
Valid Palindrome
https://leetcode.com/problems/valid-palindrome/discuss/39982/Python-in-place-two-pointer-solution.

class Solution:
    def isPalindrome(self, s):
        s = ''.join(e for e in s if e.isalnum()).lower()
        return s==s[::-1]

https://www.cnblogs.com/ilyou2049/p/11123299.html
isalnum()方法 isalpha()方法 isdigit()方法
String to Integer
https://leetcode.com/problems/string-to-integer-atoi/discuss/4673/60ms-python-solution-OJ-says-this-beats-100-python-submissions

class Solution(object):
    def myAtoi(self, s):
        """
        :type str: str
        :rtype: int
        """
     
        ls = list(s.strip())
        if len(ls) == 0 : return 0
        sign = -1 if ls[0] == '-' else 1
        if ls[0] in ['-','+'] : del ls[0]
        ret, i = 0, 0
        while i < len(ls) and ls[i].isdigit() :
            ret = ret*10 + ord(ls[i]) - ord('0')
            i += 1
        return max(-2**31, min(sign * ret,2**31-1))

Count and Say
https://leetcode.com/problems/count-and-say/discuss/16044/Simple-Python-Solution
注意是n-1和+=

     def countAndSay(self, n):
        s = '1'
        for _ in range(n-1):
            let, temp, count = s[0], '', 0
            for l in s:
                if let == l:
                    count += 1
                else:
                    temp += str(count)+let
                    let = l
                    count = 1
            temp += str(count)+let
            s = temp
        return s

Longest Common Prefix
https://leetcode.com/problems/longest-common-prefix/discuss/6918/Short-Python-Solution
注意最后return shortest

def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        if not strs:
            return ""
        shortest = min(strs,key=len)
        for i, ch in enumerate(shortest):
            for other in strs:
                if other[i] != ch:
                    return shortest[:i]
        return shortest 

3 LinkedList

Remove Nth Node From End of List
https://leetcode.com/explore/interview/card/top-interview-questions-easy/93/linked-list/603/
可以使用双指针来计算
Reverse Linked List
https://leetcode.com/explore/interview/card/top-interview-questions-easy/93/linked-list/560/
也可以考虑用递归的方法做

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

class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head or not head.next:
            return head
        p = self.reverseList(head.next)
        head.next.next = head
        head.next = None
        return p    

Palindrome Linked List
https://leetcode.com/explore/interview/card/top-interview-questions-easy/93/linked-list/772/
https://leetcode.com/problems/palindrome-linked-list/discuss/64514/5-lines-Python-O(n)-time-and-space
不考虑in place直接翻转比较

def isPalindrome(self, head):
    vals = []
    while head:
        vals += head.val,
        head = head.next
    return vals == vals[::-1]

考虑in place 用快慢指针,翻转后一半,比较前后两版
https://leetcode.com/problems/palindrome-linked-list/discuss/64689/Python-easy-to-understand-solution-with-comments-(operate-nodes-directly).
Linked List Cycle
https://leetcode.com/explore/featured/card/top-interview-questions-easy/93/linked-list/773/
用dict或者two pointer

4 Trees

Validate Binary Search Tree
https://leetcode.com/explore/featured/card/top-interview-questions-easy/94/trees/625/
iteration或者recursion或者inorder traversal

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def isValidBST(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        def helper(root, lower=float("-inf"), upper=float("inf")): 
            if not root:
                return True
            if not helper(root.left, lower, root.val):
                return False
            if not helper(root.right, root.val, upper):
                return False
            if not (lower < root.val < upper):
                return False
            return True
        return helper(root)

Symmetric Tree
https://leetcode.com/explore/interview/card/top-interview-questions-easy/94/trees/627/
使用两个root,t1, t2

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def isSymmetric(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        def isMirror(t1, t2):
            if t1 == None and t2 == None:
                return True
            if t1 == None or t2 == None:
                return False
            return t1.val == t2.val and isMirror(t1.left, t2.right) and isMirror(t1.right, t2.left)
        
        return isMirror(root, root)

Binary Tree Level Order Traversal
https://leetcode.com/explore/interview/card/top-interview-questions-easy/94/trees/628/
deque, queue, level, node
Convert Sorted Array to Binary Search Tree
https://leetcode.com/explore/interview/card/top-interview-questions-easy/94/trees/631/

class Solution(object):
    def sortedArrayToBST(self, nums):
        """
        :type nums: List[int]
        :rtype: TreeNode
        """
        if not nums:
            return None
        mid = len(nums) // 2
        node = TreeNode(nums[mid])
        node.left = self.sortedArrayToBST(nums[:mid])
        node.right = self.sortedArrayToBST(nums[mid+1:])
        return node

5 Sorting and Searching

Merge Sorted Array
https://leetcode.com/problems/merge-sorted-array/discuss/29503/Beautiful-Python-Solution
从后往前写,融合
First Bad Version
https://leetcode.com/explore/interview/card/top-interview-questions-easy/96/sorting-and-searching/774/
https://www.jiuzhang.com/solution/first-bad-version/#tag-highlight-lang-python
相邻即退出

class Solution:
    """
    @param n: An integers.
    @return: An integer which is the first bad version.
    """
    def findFirstBadVersion(self, n):
        start, end = 1, n
        while start + 1 < end:
            mid = (start + end) // 2
            if SVNRepo.isBadVersion(mid):
                end = mid
            else:
                start = mid
        if SVNRepo.isBadVersion(start):
            return start
        return end

6 Dynamic Programming

Climbing Stairs
https://leetcode.com/explore/interview/card/top-interview-questions-easy/97/dynamic-programming/569/
从下到上,使用DP

class Solution(object):
    def climbStairs(self, n):
        """
        :type n: int
        :rtype: int
        """
        if n == 1:
            return 1
        dp = [0 for i in range(n+1)]
        dp[1] = 1
        dp[2] = 2
        for i in range(3, n+1):
            dp[i] = dp[i-1] + dp[i-2]
        return dp[n]

Best Time to Buy and Sell Stock
https://leetcode.com/problems/best-time-to-buy-and-sell-stock/discuss/39049/Easy-O(n)-Python-solution
max_profit和min_price临时存

def maxProfit(prices):
    max_profit, min_price = 0, float('inf')
    for price in prices:
        min_price = min(min_price, price)
        profit = price - min_price
        max_profit = max(max_profit, profit)
    return max_profit

Maximum Subarray
https://leetcode.com/problems/maximum-subarray/discuss/20396/Easy-Python-Way
https://leetcode.com/problems/maximum-subarray/discuss/20194/A-Python-solution
从求和的角度看

class Solution(object):
    def maxSubArray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if not nums:
            return 0
        if len(nums) == 1:
            return nums[0]
        for i in range(1, len(nums)):
            if nums[i-1] > 0:
                nums[i] += nums[i-1]
        return max(nums)

House Robber
DP问题的一般解法:
Find recursive relation
Recursive (top-down)
Recursive + memo (top-down)

class Solution(object):
    def rob(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        memo = [-1 for i in range(len(nums))]
        return self.helper(nums, len(nums) - 1, memo)
    
    def helper(self, nums, i, memo):
        if i < 0:
            return 0
        if memo[i] >= 0:
            return memo[i]
        result = max(self.helper(nums, i - 2, memo) + nums[i], self.helper(nums, i - 1, memo))
        memo[i] = result
        return result

Iterative + memo (bottom-up)

class Solution(object):
    def rob(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if not nums:
            return 0
        memo = [-1 for i in range(len(nums)+1)]
        memo[0] = 0
        memo[1] = nums[0]
        for i in range(1, len(nums)):
            memo[i+1] = max(memo[i], memo[i-1]+nums[i])
        return memo[len(nums)]

Iterative + N variables (bottom-up)
https://leetcode.com/problems/house-robber/discuss/156523/From-good-to-great.-How-to-approach-most-of-DP-problems.

7 Design

Shuffle an Array
https://leetcode.com/explore/featured/card/top-interview-questions-easy/98/design/670/

class Solution:
    def __init__(self, nums):
        self.array = nums
        self.original = list(nums)

    def reset(self):
        self.array = self.original
        self.original = list(self.original)
        return self.array

    def shuffle(self):
        for i in range(len(self.array)):
            swap_idx = random.randrange(i, len(self.array))
            self.array[i], self.array[swap_idx] = self.array[swap_idx], self.array[i]
        return self.array

Min Stack
https://leetcode.com/problems/min-stack/discuss/49183/Python-one-stack-solution-without-linklist
使用[(x, cur_min),()]格式来存储,本质上是一个栈

8 Math

Count Primes
https://leetcode.com/explore/interview/card/top-interview-questions-easy/102/math/744/
https://leetcode.com/problems/count-primes/discuss/153528/Python3-99-112-ms-Explained%3A-The-Sieve-of-Eratosthenes-with-optimizations
使用根号n来计算更快,n^2会超时,用每个乘法来算,原理见下:
https://blog.csdn.net/Avan_Lau/article/details/7257566

class Solution(object):
    def countPrimes(self, n):
        """
        :type n: int
        :rtype: int
        """
        if n < 2:
            return 0
        strikes = [1] * n
        strikes[0] = 0
        strikes[1] = 0
        for i in range(2, int(n**0.5) + 1):
            if strikes[i] != 0:
                #strikes[i*i:n:i] = [0]*((n-1-i*i)//i+1)
                index = i*i
                while index < n:
                    strikes[index] = 0
                    index += i
            
        return sum(strikes)

Power of Three
https://leetcode.com/explore/interview/card/top-interview-questions-easy/102/math/745/
https://leetcode.com/problems/power-of-three/discuss/77977/Math-1-liner-no-log-with-explanation
直接找最大的那个算

def isPowerOfThree(self, n):
    return n > 0 == 3**19 % n

Roman to Integer
https://leetcode.com/problems/roman-to-integer/discuss/6537/My-Straightforward-Python-Solution
直接把每个罗马字符对应的数弄成dict

9 Others

Number of 1 Bits
https://leetcode.com/problems/number-of-1-bits/discuss/55106/Python-2-solutions.-One-naive-solution-with-built-in-functions.-One-trick-with-bit-operation
Hamming Distance
https://leetcode.com/problems/number-of-1-bits/discuss/55106/Python-2-solutions.-One-naive-solution-with-built-in-functions.-One-trick-with-bit-operation

def hammingWeight(self, n):
    """
    :type n: int
    :rtype: int
    """
    return bin(n).count('1')
def hammingWeight(self, n):
    """
    :type n: int
    :rtype: int
    """
    c = 0
    while n:
        n &= n - 1
        c += 1
    return c

Reverse Bits
https://leetcode.com/problems/reverse-bits/discuss/54748/AC-Python-44-ms-solution-bit-manipulation

class Solution:
    # @param n, an integer
    # @return an integer
    def reverseBits(self, n):
        result = 0
        for i in range(32):
            result = (result << 1) + (n & 1)
            n >>= 1
        return result

Valid Parentheses
https://leetcode.com/explore/interview/card/top-interview-questions-easy/99/others/721/
Missing Number
https://leetcode.com/explore/interview/card/top-interview-questions-easy/99/others/722/
异或的使用

class Solution(object):
    def missingNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        missing = len(nums)
        for i, num in enumerate(nums):
            missing ^= i ^ num
        return missing

你可能感兴趣的:(ZXAlgorithm - Leetcode Top Interview Questions Easy Collection刷题日记)