按Frequency的顺序刷。斜体重点或未掌握。
05/20/2022
1)1. Two Sum
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
思路:用字典(hashmap)存已经遍历过的数字,就不用再遍历一次了。<k,v>=<nums[i],i>。每经过一个数字n,去字典里找target-n, 在就返回,不在就将n存入字典。
2)680. Valid Palindrome II
Given a string s, return true if the s can be palindrome after deleting at most one character from it. 删除至多一个字母,判断剩下的字符串是不是回文。
思路:2 pointers, i从头开始,j从尾开始,如果s[i]!=s[j],检查s[i:j]和s[i+1,j+1]是不是回文,如果都不是,return False;如果有一个是,return True.
3)20. Valid Parentheses
Input: s = "()[]{}" Output: true
Input: s = "(]" Output: false
思路:建立hashmap <closing bracket, openning bracket>. mapping = {")": "(", "}": "{", "]": "["}. 建一个空List作为stack, 开始遍历,如果是一个openning bracket, 就push到stack里(append to list); 如果是closing bracket, 和stack最顶上的元素(就是最近一个被append到list的元素,stack.pop())对比,不一致就return False. 直到遍历完所有元素,stack应为空。
note: list l.pop()弹出最后一个元素,l.pop(i)弹出第i个元素
4)13. Roman to Integer
罗马数字转数字
思路:建立mapping
values = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000, "IV": 4, "IX": 9, "XL": 40, "XC": 90, "CD": 400, "CM": 900}
5)121. Best Time to Buy and Sell Stock
Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
思路:建立minprice=float('inf')和maxprofit=0,开始遍历,价格比minprice低则更新minprice,价格-minprice>max_profit则更新max_profit。
6)53. Maximum Subarray
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
思路:动态规划,遍历列表的过程中更新两个变量,current_subarray=max(num, current_subarray + num),max_subarray = max(max_subarray, current_subarray)
7)408. Valid Word Abbreviation
A string can be abbreviated by replacing any number of non-adjacent, non-empty substrings with their lengths. The lengths should not have leading zeros.
Input: word = "internationalization", abbr = "i12iz4n"
Output: true
Explanation: The word "internationalization" can be abbreviated as "i12iz4n" ("i nternational iz atio n").
思路:分别遍历word和abbreviation,字母就比较,数字就先取到最大长度,再比较;或者用regular expression
8)14. Longest Common Prefix
find the longest common prefix string amongst an array of strings.
Input: strs = ["flower","flow","flight"]
Output: "fl"
思路:找到最短的一个string,每个字母与其他string的相同位置字母比较,直到出现不同。
9)938. Range Sum of BST
Given the root node of a binary search tree and two integers low and high, return the sum of values of all nodes with a value in the inclusive range [low, high].
思路:找到树上符合特定大小的所有数字的和。binary search tree的特点是左子节点比节点小,右子节点比节点大。Depth First Search,可以Recursive或Iterative。Recursive:
def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:
def dfs(node):
nonlocal ans
if node:
if low <= node.val <= high:
ans += node.val
if low < node.val:
dfs(node.left)
if node.val < high:
dfs(node.right)
ans = 0
dfs(root)
return ans
05/21/2022
10)9. Palindrome Number
回文数
思路:将数字转化成str,逐位判断;或通过不断%10,新建一个revertnumber,判断与原数是否相等。
11)704. Binary Search
数字从小到大排列的数组,用binary search的方法找到target数字的位置,不存在则return -1.
思路:设置三个变量,left,pivot,right (lower,point,upper),二分法不断缩小范围。
12)1207. Unique Number of Occurrences
Given an array of integers arr, return true if the number of occurrences of each value in the array is unique, or false otherwise.
思路:创建字典
def uniqueOccurrences(self, arr: List[int]) -> bool:
freq_dict={a:arr.count(a) for a in arr}
freq_list=freq_dict.values()
return len(freq_list)==len(set(freq_list))
13)716. Max Stack
Design a max stack data structure that supports the stack operations and supports finding the stack's maximum element.
思路:答案是Two Stacks,存储数组(x, m),x是push进来的数字,m是当前的最大值。但是我list只存x不存m也通过了?
14)696. Count Binary Substrings
Give a binary string s, return the number of non-empty substrings that have the same number of 0's and 1's, and all the 0's and all the 1's in these substrings are grouped consecutively.
思路:group连续数字,例如s = "110001111000000", then groups = [2, 3, 4, 6]. 两个group i-1和i 组合能得到min(groups[i-1], groups[i])种连续数组。
15)217. Contains Duplicate
返回list中是否包含重复。
思路:python里很简单,直接return len(nums)>len(set(nums))
16)415. Add Strings
Input: num1 = "11", num2 = "123"
Output: "134"
思路: 1.Python里很简单,return str(int(num1)+int(num2)); 2.利用unicode, ord(n) - ord('0'); 3.数学方法一位位算,进位carry
17)937. Reorder Data in Log Files
题干比较复杂
思路:
letters.sort(key = lambda x: x.split()[1]) #when suffix is tie, sort by identifier
letters.sort(key = lambda x: x.split()[1:]) #sort by suffix
18)346. Moving Average from Data Stream
不断输入新数字,求Moving Average
思路:可以建普通List作为queue,也可以用deque()。
Note: Deques are a generalization of stacks and queues (the name is pronounced deck and is short for double-ended queue).
05/22/2022
19)21. Merge Two Sorted Lists
You are given the heads of two sorted linked lists list1 and list2. Merge the two lists in a one sorted list.
思路:
Recursive
def mergeTwoLists(self, l1, l2): if l1 is None: return l2 elif l2 is None: return l1 elif l1.val < l2.val: l1.next = self.mergeTwoLists(l1.next, l2) return l1 else: l2.next = self.mergeTwoLists(l1, l2.next) return l2
Iterative
def mergeTwoLists(self, l1, l2): prehead = ListNode(-1) prev = prehead while l1 and l2: if l1.val <= l2.val: prev.next = l1 l1 = l1.next else: prev.next = l2 l2 = l2.next prev = prev.next prev.next = l1 or l2 return prehead.next
20)412. Fizz Buzz
answer[i] == "FizzBuzz" if i is divisible by 3 and 5; "Fizz" if i is divisible by 3; "Buzz" if i is divisible by 5; i (as a string) if none of the above conditions are true.
思路:if else
21)88. Merge Sorted Array
two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively. Merge nums1 and nums2 into a single array sorted in non-decreasing order.
Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]
Explanation: The arrays we are merging are [1,2,3] and [2,5,6].
The result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1.
思路: Three Pointers, instead of start from the beginning, we start from the end. 从右边开始可以avoid overwriting numbers,降低space complexity from O(m) to O(1).
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
# Do not return anything, modify nums1 in-place instead.
# Set p1 and p2 to point to the end of their respective arrays.
p1 = m - 1
p2 = n - 1
# And move p backwards through the array, each time writing
# the smallest value pointed at by p1 or p2.
for p in range(n + m - 1, -1, -1):
if p2 < 0:
break
if p1 >= 0 and nums1[p1] > nums2[p2]:
nums1[p] = nums1[p1]
p1 -= 1
else:
nums1[p] = nums2[p2]
p2 -= 1
22)70. Climbing Stairs
爬楼梯,一次可以跨1步或2步,求n级楼梯的跨步方法数。
思路: dynamic programming, 相当于n-1级台阶的基础上跨1步,或者是n-2级台阶的基础上跨2步,return self.climbStairs(n-2)+self.climbStairs(n-1)。但是直接这样做会导致Time Limit Exceeded。所以建一个steps=[]列表,存入每一级的方法数,steps.append(steps[i-2]+steps[i-1])。
23)1507. Reformat Date
Input: date = "20th Oct 2052"
Output: "2052-10-20"
思路:建一个月份的mapping,写规则即可。
24)125. Valid Palindrome
去除所有空格和标点符号后,检查是否为回文数。
思路:2 pointers, i=0, j=len-1。s[i].isalnum()检查是否为alphanumeric, s[i].lower()转化为小写。
25)234. Palindrome Linked List
检查linked list是否回文
思路:可以遍历转化为list,或者recursive,但都是O(N)space.
Recursive:
def isPalindrome(self, head: ListNode) -> bool:
self.front_pointer = head
def recursively_check(current_node=head):
if current_node is not None:
if not recursively_check(current_node.next):
return False
if self.front_pointer.val != current_node.val:
return False
self.front_pointer = self.front_pointer.next
return True
return recursively_check()
Reverse Second Half In-place, 这个方法是O(1)space:
def isPalindrome(self, head: ListNode) -> bool:
if head is None:
return True
# Find the end of first half and reverse second half.
first_half_end = self.end_of_first_half(head)
second_half_start = self.reverse_list(first_half_end.next)
# Check whether or not there's a palindrome.
result = True
first_position = head
second_position = second_half_start
while result and second_position is not None:
if first_position.val != second_position.val:
result = False
first_position = first_position.next
second_position = second_position.next
# Restore the list and return the result.
first_half_end.next = self.reverse_list(second_half_start)
return result
def end_of_first_half(self, head):
fast = head
slow = head
while fast.next is not None and fast.next.next is not None:
fast = fast.next.next
slow = slow.next
return slow
def reverse_list(self, head):
previous = None
current = head
while current is not None:
next_node = current.next
current.next = previous
previous = current
current = next_node
return previous
26)605. Can Place Flowers
间隔插花,array中1表示已经有花,求能不能再插入n支,使花均不相邻。
Input: flowerbed = [1,0,0,0,1], n = 1
Output: true
Input: flowerbed = [1,0,0,0,1], n = 2
Output: false
思路: 中间位置,连续3个空格可以插1个,4个插1个,5个插2个,6个插2个...能插(n-1)//2个。两边比较特殊,可以在首尾分别插入0,就可以转化为中间的处理。遍历即可。
27)509. Fibonacci Number
斐波那契数列,F(0) = 0, F(1) = 1,F(n) = F(n - 1) + F(n - 2), for n > 1.
思路: 可以直接recursive, return self.fib(n-1)+self.fib(n-2), 但是这样慢, 可以建一个list把中间计算结果都存下来, fibs.append(fibs[i-2]+fibs[i-1])
28)706. Design HashMap
Design a HashMap without using any built-in hash table libraries.
思路: list中存<k,v>数组。
29)387. First Unique Character in a String
Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.
思路: 1.先将每个字母出现的频率存到dict,再从头遍历,如果count=1就return当前位置。2.一个dict存字母和第一次出现的位置,一个set存见过的字母,如果见过就从dict中删除。
30)118. Pascal's Triangle
pascal[i][j] = pascal[i-1][j-1] + pascal[i-1][j]
31)359. Logger Rate Limiter
10s内不能输出相同的message
思路:创建dict<k,v>:self.messages[message]=timestamp
32)697. Degree of an Array
数字出现的频率称为degree,找出包含最大degree的最短substring.
思路:dict<n,[indexes]>
33)344. Reverse String
翻转字符串。
思路:2 pointers,不断交换两个字符。
def reverseString(self, s):
left, right = 0, len(s) - 1
while left < right:
s[left], s[right] = s[right], s[left]
left, right = left + 1, right - 1
34)1047. Remove All Adjacent Duplicates In String
循环删除字符串中相邻重复的字符
Input: s = "abbaca"
Output: "ca"
思路:
1.generate 26 possible duplicates: duplicates = {2 * ch for ch in ascii_lowercase}, for d in duplicates: S = S.replace(d, '')
2.Stack:空list,重复就把前一个pop
35)278. First Bad Version
你可以调用一个函数isBadVersion(n),来检查这个version有没有问题。假如3是好的,4和5是坏的,那么输出4。
思路:binary search
36)543. Diameter of Binary Tree
Given the root of a binary tree, return the length of the diameter of the tree.
The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.
思路: Depth-first Search
def diameterOfBinaryTree(self, root):
self.ans = 0
def depth(p):
if not p: return 0
left, right = depth(p.left), depth(p.right)
self.ans = max(self.ans, left+right)
return 1 + max(left, right)
depth(root)
return self.ans
37)349. Intersection of Two Arrays
求两个数组的交集。
思路:
1.Python直接return list(set(nums1) & set(nums2))
2.brute-force searching
3.字典记录第一个数组,对第二个数组check是否在字典中
4.两个数组分别排序,two pointers
38)206. Reverse Linked List
逆转链表
思路:
Iterative
def reverseList(self, head: ListNode) -> ListNode:
prev = None
curr = head
while curr:
next_temp = curr.next
curr.next = prev
prev = curr
curr = next_temp
return prev
Recursive
def reverseList(self, head: ListNode) -> ListNode:
if (not head) or (not head.next):
return head
p = self.reverseList(head.next)
head.next.next = head
head.next = None
return p
39)724. Find Pivot Index
找到一个位置,位置左边所有数的和=右边所有数的和(不包括自己)
思路: Time: O(n),Space: O(1)
def pivotIndex(self, nums):
left, right = 0, sum(nums)
for index, num in enumerate(nums):
right -= num
if left == right:
return index
left += num
return -1
40)283. Move Zeroes
move all 0's to the end of it while maintaining the relative order of the non-zero elements.
Input: nums = [0,1,0,3,12]
Output: [1,3,12,0,0]
思路: 2 pointers, Time: O(n),Space: O(1)
def moveZeroes(self, nums: list) -> None:
slow = 0
for fast in range(len(nums)):
if nums[fast] != 0 and nums[slow] == 0:
nums[slow], nums[fast] = nums[fast], nums[slow]
# wait while we find a non-zero element to swap with you
if nums[slow] != 0:
slow += 1
05/25/2022
41)1275. Find Winner on a Tic Tac Toe Game
三子棋
思路:
1.brute force 8种赢的情况
2.行=[0,0,0]、列=[0,0,0]、对角线=0、反对角=0,A下一个棋子就+1,B下一个就-1,检查哪个到了3。可以拓展到n
42)953. Verifying an Alien Dictionary
Input: words = ["word","world","row"], order = "worldabcefghijkmnpqstuvxyz"
Output: false
Explanation: As 'd' comes after 'l' in this language, then words[0] > words[1], hence the sequence is unsorted.
思路: 将order建成字典,每个词和后一个词逐字比较。
43)1539. Kth Missing Positive Number
Input: arr = [2,3,4,7,11], k = 5
Output: 9
Explanation: The missing positive integers are [1,5,6,8,9,10,12,13,...]. The 5th missing positive integer is 9.
思路:
1.遍历,k不断减去missing numbers的数量直到0
2.Binary search减少运算时间,把中间数pivot和left的差值与k进行比较
44)1046. Last Stone Weight
Input: stones = [2,7,4,1,8,1]
Output: 1
Explanation:
We combine 7 and 8 to get 1 so the array converts to [2,4,1,1,1] then,
we combine 2 and 4 to get 2 so the array converts to [2,1,1,1] then,
we combine 2 and 1 to get 1 so the array converts to [1,1,1] then,
we combine 1 and 1 to get 0 so the array converts to [1] then that's the value of the last stone.
思路:
1.Array-Based Simulation,Sorted Array-Based Simulation,都需要N的二次方time complexity.
2.Heap-Based Simulation, Time complexity: O(NlogN).
use Heap data structure, returning the minimum.
def lastStoneWeight(self, stones: List[int]) -> int:
for i in range(len(stones)):
stones[i] *= -1
heapq.heapify(stones)
while len(stones) > 1:
stone_1 = heapq.heappop(stones)
stone_2 = heapq.heappop(stones)
if stone_1 != stone_2:
heapq.heappush(stones, stone_1 - stone_2)
return -heapq.heappop(stones) if stones else 0
3.bucket sort / counting sort
This approach is only viable when the maximum stone weight is small, or is at least smaller than the number of stones. Time complexity=O(N+W), where W is max weight.
建一个长度为max-weight的list,位置代表重量,值代表这个重量的石头数量,从大到小开始遍历。
05/27/2022
45)202. Happy Number
Input: n = 19
Output: true
Explanation:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
思路: 先通过分析排除infinite的情况,那么只有两种情况,最后为1(happy number)或者进入loop。
1.Detect Cycles with a HashSet
把出现过的数字存入set, 再出现就说明进入loop,return False。直到出现1,return True.
2.Floyd's Cycle-Finding Algorithm
两个pointer, slow runner走一步,fast runner走两步。
If n is a happy number, i.e. there is no cycle, then the fast runner will eventually get to 1 before the slow runner.
If n is not a happy number, then eventually the fast runner and the slow runner will be on the same number.
不断循环,直到fast runner==1或fast runner=slow runner
3.Hardcoding the Only Cycle
cycle_members = {4, 16, 37, 58, 89, 145, 42, 20}
46)243. Shortest Word Distance
Input: wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "makes", word2 = "coding"
Output: 1
思路: 遍历,更新word1_index, word2_index, shortest_distance
47)243. Shortest Word Distance
Input: low = 3, high = 7
Output: 3
Explanation: The odd numbers between 3 and 7 are [3,5,7].
思路:
1.判断high和low分别是奇数还是偶数:odds=mod(low,2)+mod(high,2),然后return (high-low+odds)//2
2.the count of odd numbers between 1 and low - 1 is low / 2, the count of odd numbers between 1 and high is (high + 1 ) / 2, return (high + 1) / 2 - low / 2
48)1260. Shift 2D Grid
Input: grid = [[1,2,3],[4,5,6],[7,8,9]], k = 1
Output: [[9,1,2],[3,4,5],[6,7,8]]
思路:
1.Simulation
2.Using Modulo Arithmetic 算出新的位置,往新的空list中填充
05/28/2022
49)1710. Maximum Units on a Truck
boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]
Input: boxTypes = [[1,3],[2,2],[3,1]], truckSize = 4
Output: 8 (13+22+1*1)
思路: boxTypes.sort(reverse=True, key=lambda x: x[1]) 或 boxTypes.sort(key=lambda x: -x[1]),然后遍历。
50)136. Single Number
Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.
思路:
1.Hash Table
A defaultdict works exactly like a normal dict, but it is initialized with a function (“default factory”) that takes no arguments and provides the default value for a nonexistent key. A defaultdict will never raise a KeyError. Any key that does not exist gets the value returned by the default factory.
def singleNumber(self, nums: List[int]) -> int:
hash_table = defaultdict(int)
for i in nums:
hash_table[i] += 1
for i in hash_table:
if hash_table[i] == 1:
return i
2.Math
return 2 * sum(set(nums)) - sum(nums)
3.Bit Manipulation
def singleNumber(self, nums):
a = 0
for i in nums:
a ^= i
return a
51)171. Excel Sheet Column Number
Input: columnTitle = "A"
Output: 1
Input: columnTitle = "AB"
Output: 28
思路:
For example, if we want to get the decimal value of string "1337", we can iteratively find the result by scanning the string from left to right as follows:
'1' = 1
'13' = (1 x 10) + 3 = 13
'133' = (13 x 10) + 3 = 133
'1337' = (133 x 10) + 7 = 1337
For a title "LEET":
L = 12
E = (12 x 26) + 5 = 317
E = (317 x 26) + 5 = 8247
T = (8247 x 26) + 20 = 214442
def titleToNumber(self, s: str) -> int:
result = 0
n = len(s)
for i in range(n):
result = result * 26
result += (ord(s[i]) - ord('A') + 1)
return result
52)169. Majority Element
Given an array nums of size n, return the majority element. The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array.
思路:
1.HashMap
def majorityElement(self, nums):
counts = collections.Counter(nums)
return max(counts.keys(), key=counts.get)
2.Sorting
def majorityElement(self, nums):
nums.sort()
return nums[len(nums)//2]
3.Boyer-Moore Voting Algorithm
If we had some way of counting instances of the majority element as +1+1 and instances of any other element as -1−1, summing them would make it obvious that the majority element is indeed the majority element.
def majorityElement(self, nums):
count = 0
candidate = None
for num in nums:
if count == 0:
candidate = num
count += (1 if num == candidate else -1)
return candidate
53)977. Squares of a Sorted Array
Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.
思路: Two Pointer,left/right, 先建一个全是0的list, 然后从大到小填数。
54)1854. Maximum Population Year
You are given a 2D integer array logs where each logs[i] = [birthi, deathi] indicates the birth and death years of the ith person. Return the earliest year with the maximum population.
Input: logs = [[1950,1961],[1960,1971],[1970,1981]]
Output: 1960
Explanation:
The maximum population is 2, and it had happened in years 1960 and 1970.
The earlier year between them is 1960.
思路:
1.建空list,存(year,+-1)的array,sort,遍历
2.建dictioanry,<year,population>
55)228. Summary Ranges
Input: nums = [0,1,2,4,5,7]
Output: ["0->2","4->5","7"]
思路:2 pointers
56)26. Remove Duplicates from Sorted Array
修改数列nums,使前n位符合remove duplicate之后的list,后面的数字不用管,nums总长度不变,并return数字n
思路:2 pointers
57)242. Valid Anagram
判断是否为异序词, 即包含同样的字母
Input: s = "anagram", t = "nagaram"
Output: true
1.Sort, return sorted(s) == sorted(t)
2.Frequency Counter, dic1[item] = dic1.get(item, 0) + 1
05/30/2022
58)67. Add Binary
Input: a = "11", b = "1"
Output: "100"
思路:
1.内置函数
return '{0:b}'.format(int(a, 2) + int(b, 2))
2.Bit-by-Bit Computation
传统二进制算法
3.Bit Manipulation
def addBinary(self, a, b) -> str:
x, y = int(a, 2), int(b, 2)
while y:
x, y = x ^ y, (x & y) << 1
return bin(x)[2:]
59)1304. Find N Unique Integers Sum up to Zero
Given an integer n, return any array containing n unique integers such that they add up to 0.
思路: return range(1 - n, n, 2)
60)1822. Sign of the Product of an Array
判断一个Array里数字乘积的正负
思路:从1开始,遇正不变,遇0 return0,遇负乘-1
61)69. Sqrt(x)
Input: x = 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since the decimal part is truncated, 2 is returned.
思路:
1.Pocket Calculator Algorithm
def mySqrt(self, x):
if x < 2:
return x
left = int(e**(0.5 * log(x)))
right = left + 1
return left if right * right > x else right
2.Binary Search
left, right = 2, x // 2, pivot = left + (right - left) // 2
3.Recursion + Bit Shifts
def mySqrt(self, x):
if x < 2:
return x
left = self.mySqrt(x >> 2) << 1
right = left + 1
return left if right * right > x else right
Note: self.mySqrt(x >> 2) << 1 is equal to self.mySqrt(x/4)*2
x << y Returns x with the bits shifted to the left by y places (and new bits on the right-hand-side are zeros). This is the same as multiplying x by 2**y.
x >> y Returns x with the bits shifted to the right by y places. This is the same as dividing x by 2**y.
4.Newton's Method
def mySqrt(self, x):
if x < 2:
return x
x0 = x
x1 = (x0 + x / x0) / 2
while abs(x0 - x1) >= 1:
x0 = x1
x1 = (x0 + x / x0) / 2
return int(x1)
62)766. Toeplitz Matrix
A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same elements.
思路:
1.Group by Category
two coordinates are on the same diagonal if and only if r1 - c1 == r2 - c2. remember the value of that diagonal as groups[r-c]
2.Compare With Top-Left Neighbor
def isToeplitzMatrix(self, matrix):
return all(r == 0 or c == 0 or matrix[r-1][c-1] == val
for r, row in enumerate(matrix)
for c, val in enumerate(row))
63)1920. Build Array from Permutation
Input: nums = [0,2,1,5,3,4]
Output: [0,1,2,4,5,3]
Explanation: The array ans is built as follows:
ans = [nums[nums[0]], nums[nums[1]], nums[nums[2]], nums[nums[3]], nums[nums[4]], nums[nums[5]]]
= [nums[0], nums[2], nums[1], nums[5], nums[3], nums[4]]
= [0,1,2,4,5,3]
要求O(1) space, not to use extra space, replace in place
思路:
用余数保存原来的值
def buildArray(nums: List[int]) -> List[int]:
q = len(nums)
for i,c in enumerate(nums):
nums[i] += q * (nums[c] % q)
for i,_ in enumerate(nums):
nums[i] //= q
return nums
64)101. Symmetric Tree
1.Recursive
def isSymmetric(self, root):
def isSym(L,R):
if L and R and L.val == R.val:
return isSym(L.left, R.right) and isSym(L.right, R.left)
return L == R
return not root or isSym(root.left, root.right)
2.Iterative
def isSymmetric(self, root):
queue = [root]
while queue:
values = [i.val if i else None for i in queue]
if values != values[::-1]: return False
queue = [child for i in queue if i for child in (i.left, i.right)]
return True
65)1656. Design an Ordered Stream
描述比较奇怪的题,跳过
66)1200. Minimum Absolute Difference
Given an array of distinct integers arr, find all pairs of elements with the minimum absolute difference of any two elements.
Input: arr = [3,8,-10,23,19,-4,-14,27]
Output: [[-14,-10],[19,23],[23,27]]
思路:
1.Sort + Traversals
2.Counting Sort
设置一个长度为max-min+1,元素均为0的list,然后遍历原array, 数字对应的位置改为1。例如arr=[-2,1,5],那么line=[1,0,0,1,0,0,0,1]
def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]:
min_element = min(arr)
max_element = max(arr)
shift = -min_element
line = [0] * (max_element - min_element + 1)
answer = []
for num in arr:
line[num + shift] = 1
min_pair_diff = max_element - min_element
prev = 0
for curr in range(1, max_element + shift + 1):
if line[curr] == 0:
continue
if curr - prev == min_pair_diff:
answer.append([prev - shift, curr - shift])
elif curr - prev < min_pair_diff:
answer = [[prev - shift, curr - shift]]
min_pair_diff = curr - prev
prev = curr
return answer
05/31/2022
67)1009. Complement of Base 10 Integer
The complement of an integer is the integer you get when you flip all the 0's to 1's and all the 1's to 0's in its binary representation.
Input: n = 5
Output: 2
Explanation: 5 is "101" in binary, with complement "010" in binary, which is 2 in base-10.
思路:
x^y Does a "bitwise exclusive or". Each bit of the output is the same as the corresponding bit in x if that bit in y is 0, and it's the complement of the bit in x if that bit in y is 1. 或非运算,如果 y 对应位是0,那么结果位取 x 的对应位,如果 y 对应位是1,取 x 对应位的补
1.Flip Bit by Bit
def bitwiseComplement(self, N: int) -> int:
if N == 0:
return 1
todo, bit = N, 1
while todo:
# flip current bit
N = N ^ bit
# prepare for the next run
bit = bit << 1
todo = todo >> 1
return N
2.Compute Bit Length and Construct 1-bits Bitmask
def bitwiseComplement(self, N: int) -> int:
if N == 0:
return 1
# l is a length of N in binary representation
l = floor(log2(N)) + 1
# bitmask has the same length as N and contains only ones 1...1
bitmask = (1 << l) - 1
# flip all bits
return bitmask ^ N
3.Built-in Functions to Construct 1-bits Bitmask
return (1 << N.bit_length()) - 1 - N if N else 1
4.highestOneBit OpenJDK algorithm from Hacker's Delight
def bitwiseComplement(self, N: int) -> int:
if N == 0:
return 1
# bitmask has the same length as N and contains only ones 1...1
bitmask = N
bitmask |= (bitmask >> 1)
bitmask |= (bitmask >> 2)
bitmask |= (bitmask >> 4)
bitmask |= (bitmask >> 8)
bitmask |= (bitmask >> 16)
# flip all bits
return bitmask ^ N
68)703. Kth Largest Element in a Stream
Input
["KthLargest", "add", "add", "add", "add", "add"]
[[3, [4, 5, 8, 2]], [3], [5], [10], [9], [4]]
Output
[null, 4, 5, 5, 8, 8]
思路: Heap
堆是一种基本的数据结构,堆的结构是一棵完全二叉树,并且满足堆积的性质:每个节点(叶节点除外)的值都大于等于(或都小于等于)它的子节点。
def __init__(self, k: int, nums: List[int]):
self.k = k
self.heap = nums
heapq.heapify(self.heap)
while len(self.heap) > k:
heapq.heappop(self.heap)
def add(self, val: int) -> int:
heapq.heappush(self.heap, val)
if len(self.heap) > self.k:
heapq.heappop(self.heap)
return self.heap[0]
69)496. Next Greater Element I
Input: nums1 = [4,1,2], nums2 = [1,3,4,2]
Output: [-1,3,-1]
Explanation: The next greater element for each value of nums1 is as follows:
- 4 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1.
- 1 is underlined in nums2 = [1,3,4,2]. The next greater element is 3.
2 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1.
思路:Stack
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:greater_map = {x : -1 for x in nums1} stack = [] for num in nums2: while stack and stack[-1] < num: prev_num = stack.pop() if prev_num in greater_map: greater_map[prev_num] = num stack.append(num) return [greater_map[x] for x in nums1]
stack里的数字一定是从大到小的,因为如果后面的比前面的大,前面的已经被pop了。
70)155. Min Stack
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
思路: the point is to retrieving the minimum element in constant time, 所以不光存储value,而是存储(value, current_minimum)数组在list中。
71)231. Power of Two
判断一个数是否是2的n次方
思路:除了不断除以2的方法外,还可以用bit:a power of two in binary representation is one 1-bit, followed by some zeros.
1.Bitwise Operators : Get the Rightmost 1-bit
def isPowerOfTwo(self, n):
if n == 0:
return False
return n & (-n) == n
x & (-x) would keep that rightmost 1-bit and set all the other bits to 0.
2.Bitwise operators : Turn off the Rightmost 1-bit
def isPowerOfTwo(self, n):
if n == 0:
return False
return n & (n - 1) == 0
x & (x - 1) sets this 1-bit to zero
72)219. Contains Duplicate II
Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k.
思路:
1.建k长度list作为window,不断比较。会超时。
2.Binary Search Tree. A BST supports search, delete and insert operations all in O(\log k)O(logk) time, where kk is the number of elements in the BST.
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
from sortedcontainers import SortedList
tree = SortedList()
for idx, val in enumerate(nums):
if idx > k:
tree.remove(nums[idx - k - 1])
left_index = tree.bisect_left(val)
right_index = tree.bisect_right(val)
if left_index != right_index:
return True
tree.add(val)
return False
3.Hash Table: <value,index>键值对,检查与前一个index的差值。最优解法,不超时。
73)905. Sort Array By Parity
Given an integer array nums, move all the even integers at the beginning of the array followed by all the odd integers.
Input: nums = [3,1,2,4]
Output: [2,4,3,1]
Explanation: The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.
思路:return ([x for x in A if x % 2 == 0] + [x for x in A if x % 2 == 1])
74)268. Missing Number
Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.
思路:
1.Sort
2.HashSet
3.Bit Manipulation
def missingNumber(self, nums):
missing = len(nums)
for i, num in enumerate(nums):
missing ^= i ^ num
return missing
4.Gauss' Formula
def missingNumber(self, nums):
expected_sum = len(nums)*(len(nums)+1)//2
actual_sum = sum(nums)
return expected_sum - actual_sum
75)1160. Find Words That Can Be Formed by Characters
You are given an array of strings words and a string chars.
A string is good if it can be formed by characters from chars (each character can only be used once).
Return the sum of lengths of all good strings in words.
Input: words = ["cat","bt","hat","tree"], chars = "atach"
Output: 6
Explanation: The strings that can be formed are "cat" and "hat" so the answer is 3 + 3 = 6.
def countCharacters(self, words: List[str], chars: str) -> int:
ans=0
for word in words:
for ch in word:
if word.count(ch)>chars.count(ch):
break
else:
ans+=len(word)
return ans
76)258. Add Digits
Given an integer num, repeatedly add all its digits until the result has only one digit, and return it.
Input: num = 38
Output: 2
Explanation: The process is
38 --> 3 + 8 --> 11
11 --> 1 + 1 --> 2
Since 2 has only one digit, return it.
思路:
1.while
2.math
def addDigits(self, num: int) -> int:
if num == 0:
return 0
if num % 9 == 0:
return 9
return num % 9
which equals to
def addDigits(self, num: int) -> int:
return 1 + (num - 1) % 9 if num else 0
77)35. Search Insert Position
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
Input: nums = [1,3,5,6], target = 5
Output: 2
Input: nums = [1,3,5,6], target = 2
Output: 1
思路:要求O(log n) runtime, 需要binary search
06/01/2022
78)266. Palindrome Permutation
Given a string s, return true if a permutation of the string could form a palindrome. 判断一个字符串重组能否成为回文
思路:
return sum(v % 2 for v in collections.Counter(s).values()) < 2
79)270. Closest Binary Search Tree Value
Given the root of a binary search tree and a target value, return the value in the BST that is closest to the target.
BST左<root<右
思路:
1.Recursive Inorder + Linear search
def closestValue(self, root: TreeNode, target: float) -> int:
def inorder(r: TreeNode):
return inorder(r.left) + [r.val] + inorder(r.right) if r else []
return min(inorder(root), key = lambda x: abs(target - x))
2.Iterative Inorder
def closestValue(self, root: TreeNode, target: float) -> int:
stack, pred = [], float('-inf')
while stack or root:
while root:
stack.append(root)
root = root.left
root = stack.pop()
if pred <= target and target < root.val:
return min(pred, root.val, key = lambda x: abs(target - x))
pred = root.val
root = root.right
return pred
3.Binary Search
def closestValue(self, root: TreeNode, target: float) -> int:
closest = root.val
while root:
closest = min(root.val, closest, key = lambda x: abs(target - x))
root = root.left if target < root.val else root.right
return closest
80)1560. Most Visited Sector in a Circular Track
Input: n = 4, rounds = [1,3,1,2]
Output: [1,2]
Explanation: The marathon starts at sector 1. The order of the visited sectors is as follows:
1 --> 2 --> 3 (end of round 1) --> 4 --> 1 (end of round 2) --> 2 (end of round 3 and the marathon)
We can see that both sectors 1 and 2 are visited twice and they are the most visited sectors. Sectors 3 and 4 are visited only once.
def mostVisited(self, n: int, rounds: List[int]) -> List[int]:
start=rounds[0]
end=rounds[-1]
if start<=end:
return list(range(start,end+1))
else:
return list(range(1,end+1))+list(range(start,n+1))
Note: list(range(start,end+1)) equals to [*range(start,end+1)]
81)1636. Sort Array by Increasing Frequency
Given an array of integers nums, sort the array in increasing order based on the frequency of the values. If multiple values have the same frequency, sort them in decreasing order.
思路:
def frequencySort(self, A):
count = collections.Counter(A)
return sorted(A, key=lambda x: (count[x], -x))
82)191. Number of 1 Bits
Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight).
思路:除了遍历之外
1.build in function
def hammingWeight(self, n):
return bin(n).count('1')
2.bit operation
def hammingWeight(self, n):
c = 0
while n:
n &= n - 1
c += 1
return c
83)246. Strobogrammatic Number
Given a string num which represents an integer, return true if num is a strobogrammatic number.
A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).
Input: num = "69"
Output: true
思路:存hashmap, 2 pointers左右两边开始比较
84)897. Increasing Order Search Tree
Given the root of a binary search tree, rearrange the tree in in-order so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only one right child.
思路:
1.In-Order Traversal
def increasingBST(self, root):
def inorder(node):
if node:
yield from inorder(node.left)
yield node.val
yield from inorder(node.right)
ans = cur = TreeNode(None)
for v in inorder(root):
cur.right = TreeNode(v)
cur = cur.right
return ans.right
2.Traversal with Relinking
def increasingBST(self, root):
def inorder(node):
if node:
inorder(node.left)
node.left = None
self.cur.right = node
self.cur = node
inorder(node.right)
ans = self.cur = TreeNode(None)
inorder(root)
return ans.right
85)350. Intersection of Two Arrays II
Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must appear as many times as it shows in both arrays and you may return the result in any order.
思路:除了内置函数外,可以用hashmap存nums1的counter,然后遍历nums2去对应
86)392. Is Subsequence
A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., "ace" is a subsequence of "abcde" while "aec" is not).
思路:
1.Divide and Conquer with Greedy
贪心算法(greedy algorithm),又称贪婪算法,是一种在每一步选择中都采取在当前状态下最好或最优(即最有利)的选择,从而希望导致结果是最好或最优的算法。比如在旅行推销员问题中,如果旅行员每次都选择最近的城市,那这就是一种贪心算法。
贪心算法在有最优子结构的问题中尤为有效。最优子结构的意思是局部最优解能决定全局最优解。简单地说,问题能够分解成子问题来解决,子问题的最优解能递推到最终问题的最优解。
贪心算法与动态规划的不同在于它对每个子问题的解决方案都做出选择,不能回退。动态规划则会保存以前的运算结果,并根据以前的结果对当前进行选择,有回退功能。
def isSubsequence(self, s: str, t: str) -> bool:
LEFT_BOUND, RIGHT_BOUND = len(s), len(t)
def rec_isSubsequence(left_index, right_index):
# base cases
if left_index == LEFT_BOUND:
return True
if right_index == RIGHT_BOUND:
return False
# consume both strings or just the target string
if s[left_index] == t[right_index]:
left_index += 1
right_index += 1
return rec_isSubsequence(left_index, right_index)
return rec_isSubsequence(0, 0)
2.Two-Pointers
def isSubsequence(self, s: str, t: str) -> bool:
LEFT_BOUND, RIGHT_BOUND = len(s), len(t)
p_left = p_right = 0
while p_left < LEFT_BOUND and p_right < RIGHT_BOUND:
# move both pointers or just the right pointer
if s[p_left] == t[p_right]:
p_left += 1
p_right += 1
return p_left == LEFT_BOUND
06/02/2022
87)705. Design HashSet
Design a HashSet without using any built-in hash table libraries.
Implement MyHashSet class:
void add(key) Inserts the value key into the HashSet.
bool contains(key) Returns whether the value key exists in the HashSet or not.
void remove(key) Removes the value key in the HashSet. If key does not exist in the HashSet, do nothing.
思路:
1.LinkedList as Bucket
class MyHashSet(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.keyRange = 769
self.bucketArray = [Bucket() for i in range(self.keyRange)]
def _hash(self, key):
return key % self.keyRange
def add(self, key):
"""
:type key: int
:rtype: None
"""
bucketIndex = self._hash(key)
self.bucketArray[bucketIndex].insert(key)
def remove(self, key):
"""
:type key: int
:rtype: None
"""
bucketIndex = self._hash(key)
self.bucketArray[bucketIndex].delete(key)
def contains(self, key):
"""
Returns true if this set contains the specified element
:type key: int
:rtype: bool
"""
bucketIndex = self._hash(key)
return self.bucketArray[bucketIndex].exists(key)
class Node:
def __init__(self, value, nextNode=None):
self.value = value
self.next = nextNode
class Bucket:
def __init__(self):
# a pseudo head
self.head = Node(0)
def insert(self, newValue):
# if not existed, add the new element to the head.
if not self.exists(newValue):
newNode = Node(newValue, self.head.next)
# set the new head.
self.head.next = newNode
def delete(self, value):
prev = self.head
curr = self.head.next
while curr is not None:
if curr.value == value:
# remove the current node
prev.next = curr.next
return
prev = curr
curr = curr.next
def exists(self, value):
curr = self.head.next
while curr is not None:
if curr.value == value:
# value existed already, do nothing
return True
curr = curr.next
return False
# Your MyHashSet object will be instantiated and called as such:
# obj = MyHashSet()
# obj.add(key)
# obj.remove(key)
# param_3 = obj.contains(key)
2.Binary Search Tree (BST) as Bucket
class MyHashSet:
def __init__(self):
"""
Initialize your data structure here.
"""
self.keyRange = 769
self.bucketArray = [Bucket() for i in range(self.keyRange)]
def _hash(self, key) -> int:
return key % self.keyRange
def add(self, key: int) -> None:
bucketIndex = self._hash(key)
self.bucketArray[bucketIndex].insert(key)
def remove(self, key: int) -> None:
"""
:type key: int
:rtype: None
"""
bucketIndex = self._hash(key)
self.bucketArray[bucketIndex].delete(key)
def contains(self, key: int) -> bool:
"""
Returns true if this set contains the specified element
:type key: int
:rtype: bool
"""
bucketIndex = self._hash(key)
return self.bucketArray[bucketIndex].exists(key)
class Bucket:
def __init__(self):
self.tree = BSTree()
def insert(self, value):
self.tree.root = self.tree.insertIntoBST(self.tree.root, value)
def delete(self, value):
self.tree.root = self.tree.deleteNode(self.tree.root, value)
def exists(self, value):
return (self.tree.searchBST(self.tree.root, value) is not None)
class TreeNode:
def __init__(self, value):
self.val = value
self.left = None
self.right = None
class BSTree:
def __init__(self):
self.root = None
def searchBST(self, root: TreeNode, val: int) -> TreeNode:
if root is None or val == root.val:
return root
return self.searchBST(root.left, val) if val < root.val \
else self.searchBST(root.right, val)
def insertIntoBST(self, root: TreeNode, val: int) -> TreeNode:
if not root:
return TreeNode(val)
if val > root.val:
# insert into the right subtree
root.right = self.insertIntoBST(root.right, val)
elif val == root.val:
return root
else:
# insert into the left subtree
root.left = self.insertIntoBST(root.left, val)
return root
def successor(self, root):
"""
One step right and then always left
"""
root = root.right
while root.left:
root = root.left
return root.val
def predecessor(self, root):
"""
One step left and then always right
"""
root = root.left
while root.right:
root = root.right
return root.val
def deleteNode(self, root: TreeNode, key: int) -> TreeNode:
if not root:
return None
# delete from the right subtree
if key > root.val:
root.right = self.deleteNode(root.right, key)
# delete from the left subtree
elif key < root.val:
root.left = self.deleteNode(root.left, key)
# delete the current node
else:
# the node is a leaf
if not (root.left or root.right):
root = None
# the node is not a leaf and has a right child
elif root.right:
root.val = self.successor(root)
root.right = self.deleteNode(root.right, root.val)
# the node is not a leaf, has no right child, and has a left child
else:
root.val = self.predecessor(root)
root.left = self.deleteNode(root.left, root.val)
return root
# Your MyHashSet object will be instantiated and called as such:
# obj = MyHashSet()
# obj.add(key)
# obj.remove(key)
# param_3 = obj.contains(key)
88)141. Linked List Cycle
Given head, the head of a linked list, determine if the linked list has a cycle in it.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter.
Return true if there is a cycle in the linked list. Otherwise, return false.
思路:
1.Hash Table
把经过的head(注意是head不是head.val)都存入set,如果再见到,就说明有loop
2.Floyd's Cycle Finding Algorithm
def hasCycle(self, head: ListNode) -> bool:
if head is None:
return False
slow = head
fast = head.next
while slow != fast:
if fast is None or fast.next is None:
return False
slow = slow.next
fast = fast.next.next
return True
89)1086. High Five
Given a list of the scores of different students, items, where items[i] = [IDi, scorei] represents one score from a student with IDi, calculate each student's top five average.
思路:
1.Sorting+Hashmap
def highFive(self, items: List[List[int]]) -> List[List[int]]:
d = collections.defaultdict(list)
for student, score in items:
d[student].append(score)
for student in d:
d[i]=sorted(d[i])[-5:]
return [[i,sum(d[i]) // 5] for i in d]
or
def highFive(self, items: List[List[int]]) -> List[List[int]]:
D = collections.defaultdict(list)
for student, score in items:
bisect.insort(D[student], score) # insert in a list in increasing order.
return [[student, sum(D[student][-5:])//5] for student in D]
2.Map and Max Heap
3.Map and Min Heap
heapq — Heap queue algorithm
def highFive(self, items: List[List[int]]) -> List[List[int]]:
d = collections.defaultdict(list)
for idx, val in items:
heapq.heappush(d[idx], val)
if len(d[idx]) > 5:
heapq.heappop(d[idx])
res = [[i, sum(d[i]) // len(d[i])] for i in sorted(d)]
return res
90)844. Backspace String Compare
Given two strings s and t, return true if they are equal when both are typed into empty text editors. '#' means a backspace character.
Note that after backspacing an empty text, the text will continue empty.
思路:
1.Build String
2.Two Pointer
3.Reduce
functools.reduce(function, iterable[, initializer])
from functools import reduce
reduce(fn,list)
example:
scores = [1,2,3,4,5]
total = reduce(lambda a, b: a + b, scores)
print(total)
a=1, b=2, 1+2=3
a=3, b=3, 3+3=6
a=6, b=4, 6+4=10
a=10, b=5, 10+5=15
output15
def backspaceCompare(self, S, T):
back = lambda res, c: res[:-1] if c == '#' else res + c
return reduce(back, S, "") == reduce(back, T, "")
91)997. Find the Town Judge
In a town, there are n people labeled from 1 to n. There is a rumor that one of these people is secretly the town judge.
If the town judge exists, then:
The town judge trusts nobody.
Everybody (except for the town judge) trusts the town judge.
There is exactly one person that satisfies properties 1 and 2.
You are given an array trust where trust[i] = [ai, bi] representing that the person labeled ai trusts the person labeled bi.
Return the label of the town judge if the town judge exists and can be identified, or return -1 otherwise.
思路:
1.Two Arrays
两个长度为N的array,存每个人的trust数量和被trust数量
2.One Array
一个长度为N的array,存trust score(trust-1,被trust+1),score=N-1就是judge
06/03/2022
92)290. Word Pattern
Given a pattern and a string s, find if s follows the same pattern.
Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in s.
Input: pattern = "abba", s = "dog cat cat dog"
Output: true
思路:hashmap, for c, w in zip(pattern, words)
93)345. Reverse Vowels of a String
Given a string s, reverse only all the vowels in the string and return it.
The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in both cases.
Input: s = "leetcode"
Output: "leotcede"
思路:
1.Two pointers
从左右两边同时开始找元音,遇到就交换
2.regular expression
def reverseVowels(self, s):
vowels = re.findall('(?i)[aeiou]', s)
return re.sub('(?i)[aeiou]', lambda m: vowels.pop(), s)
or
def reverseVowels(self, s):
vowels = (c for c in reversed(s) if c in 'aeiouAEIOU')
return re.sub('(?i)[aeiou]', lambda m: next(vowels), s)
94)1413. Minimum Value to Get Positive Step by Step Sum
就是求accumulated sum的最小值
06/04/2022
95)859. Buddy Strings
Given two strings s and goal, return true if you can swap two letters in s so the result is equal to goal, otherwise, return false.
Swapping letters is defined as taking two indices i and j (0-indexed) such that i != j and swapping the characters at s[i] and s[j].
For example, swapping at indices 0 and 2 in "abcd" results in "cbad".
思路:
两种情况,一种是s=goal,且有一个字母出现两次(交换完还和原来一样),另一种是遍历直到有两个字母不一样,记录字母和位置,对比。
96)836. Rectangle Overlap
Given two axis-aligned rectangles rec1 and rec2, return true if they overlap, otherwise return false.
Input: rec1 = [0,0,2,2], rec2 = [1,1,3,3]
Output: true
思路:
横竖都有intersect, 横:min(p_right, q_right) > max(p_left, q_left)
97)1002. Find Common Characters
Given a string array words, return an array of all characters that show up in all strings within the words (including duplicates). You may return the answer in any order.
思路:
简单版就是存第一个word的所有字,后面没出现就remove
或
def commonChars(self, A):
res = collections.Counter(A[0])
for a in A:
res &= collections.Counter(a)
return list(res.elements())
相当于
def commonChars(self, A):
return list(reduce(collections.Counter.__and__, map(collections.Counter, A)).elements())
98)66. Plus One
You are given a large integer represented as an integer array digits, where each digits[i] is the ith digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0's.
Input: digits = [9]
Output: [1,0]
Explanation: The array represents the integer 9.
Incrementing by one gives 9 + 1 = 10.
Thus, the result should be [1,0].
思路:从左到右遍历进位
99)28. Implement strStr()
Given two strings needle and haystack, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Input: haystack = "hello", needle = "ll"
Output: 2
思路:
遍历比较即可,注意如果切片haystack[i:i+len(needle)]的话,时间复杂度是O(n * h)where h is size of haystack. 所以如果要optimize,不要切片。
100)205. Isomorphic Strings
Given two strings s and t, determine if they are isomorphic.
Two strings s and t are isomorphic if the characters in s can be replaced to get t.
Input: s = "egg", t = "add"
Output: true
思路:hashmap
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。