11. Container With Most Water
method: 2 pointers
1 i: left pointer, j: right pointer, at both side
2 this may have the largest value, then i to right, j to left
3 until i >= j, stop loops and return result
python
class Solution:
def maxArea(self, height: List[int]) -> int:
i = 0
j = len(height)-1
res = 0
while(i < j):
res = max(res, min(height[i], height[j])*(j-i))
if height[i] < height[j]:
i = i+1
else:
j = j-1
return res
JS:
var maxArea = function(height) {
let i = 0;
let j = height.length - 1;
let res = 0;
while (i < j) {
res = Math.max(res, Math.min(height[i], height[j]) * (j - i));
height[i] < height[j] ? i++ : j--;
}
return res
};
12. Integer to Roman
method: string and math
class Solution:
def intToRoman(self, num: int) -> str:
value = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
roman = ["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"]
res = ""
for idx, val in enumerate(value):
res += (num // val) * roman[idx] # how many romans
num %= val
return res
13. Roman to Integer
method: string
### method1: 之前的太繁琐
# 这样写不符合程序设计,虽然可读,但不简洁。
class Solution:
def romanToInt(self, s: str) -> int:
num = 0
i = 0
while i < len(s):
if i < len(s) and s[i] == 'M':
num += 1000
i += 1
if i < len(s) - 1 and s[i] == 'C' and s[i + 1] == 'M':
num += 900
i += 2
if i < len(s) and s[i] == 'D':
num += 500
i += 1
if i < len(s) - 1 and s[i] == 'C' and s[i + 1] == 'D':
num += 400
i += 2
if i < len(s) and s[i] == 'C':
num += 100
i += 1
if i < len(s) - 1 and s[i] == 'X' and s[i + 1] == 'C':
num += 90
i += 2
if i < len(s) and s[i] == 'L':
num += 50
i += 1
if i < len(s) - 1 and s[i] == 'X' and s[i + 1] == 'L':
num += 40
i += 2
if i < len(s) and s[i] == 'X':
num += 10
i += 1
if i < len(s) - 1 and s[i] == 'I' and s[i + 1] == 'X':
num += 9
i += 2
if i < len(s) and s[i] == 'V':
num += 5
i += 1
if i < len(s) - 1 and s[i] == 'I' and s[i + 1] == 'V':
num += 4
i += 2
if i < len(s) and s[i] == 'I':
num += 1
i += 1
return num
method 2: 2 pointers
prev指向curr的前一个数。
例一:IV:I 比 V 小, 那么执行if语句, 按正常循环,当遍历到 V时,结果为6,可见多加了一个 I,相当于 V + I = 6,
但是因为prev < curr,说明不对,需要修改错误,那么就应该是 6 - I * 2 = 4
例二:VI, 按照正常情况, 不经过if语句, 直接输出6
class Solution:
def romanToInt(self, s: str) -> int:
table = dict(I=1, V=5, X=10, L=50, C=100, D=500, M=1000)
res = 0
prev = table['M']
for c in s:
curr = table[c]
res += curr
if prev < curr:
res -= prev * 2
prev = curr
return res
/**
* @param {string} s
* @return {number}
*/
var romanToInt = function(s) {
const table = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000
};
let res = 0, prev = table['M'];
for (c of s) { // not c in s
let curr = table[c];
res += curr;
if (prev < curr) {
res -= prev * 2;
}
prev = curr
}
return res
};
14. Longest Common Prefix
method: zip
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
prefix = []
# zip to [('f', 'f', 'f'), ('l', 'l', 'l'), ('o', 'o', 'i'), ('w', 'w', 'g')]
for item in zip(*strs):
if len(set(item)) != 1:
break
else:
prefix.append(item[0])
return ''.join(prefix)
15. 3Sum
method: 2 pointers
1 prepare a set
2 sort the array
3 for each i loop, use 2 pointers to reduce time in sorted array
4 use set to avoid repeating
Python:
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
output = set()
nums.sort()
for i in range(len(nums)):
low, high = i + 1, len(nums) - 1
while low < high:
num_sum = nums[i] + nums[low] + nums[high]
if num_sum == 0:
output.add((nums[i], nums[low], nums[high]))
low += 1
high -= 1
elif num_sum > 0:
high -= 1
else:
low += 1
return output
JS: optimized 2 pointers
var threeSum = function(nums) {
nums.sort((a, b) => a - b)
const res = [];
for(let i = 0; i < nums.length; i++) {
if(nums[i] === nums[i - 1]) {
continue // skip same elements to avoid duplicate triplets
}
let start = i+1, end = nums.length - 1
while(start < end) {
const sum = nums[i] + nums[start] + nums[end]
if(sum === 0) {
res.push([nums[i], nums[start], nums[end]]);
start++
end--
while (start < end && nums[start] === nums[start - 1]) {
start += 1; // skip same elements to avoid duplicate triplets
}
while (start < end && nums[end] === nums[end + 1]) {
end -= 1; // skip same elements to avoid duplicate triplets
}
} else if (sum < 0) {
start++;
} else {
end--;
}
}
}
return res;
};
16. 3Sum Closest
method: 2 pointers => leetcode 15 -> 16
1 prepare a res = infinity
2 sort the array
3 for each i in loop, use 2 pointers to find the closest
4 if equals to target, return target
5 else return closest
6 if low >= high, output res
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
res = float('inf')
nums.sort()
for i in range(len(nums)):
lo, hi = i + 1, len(nums) - 1
while lo < hi:
three = nums[i] + nums[lo] + nums[hi]
if three == target:
return target
if abs(three - target) < abs(res - target):
res = three
if three < target:
lo += 1
else:
hi -= 1
return res
17. Letter Combinations of a Phone Number
method: hash map
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
if digits == "":
return []
numtolet = {"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"],
}
# e.g. digits = "23"
result = [''] # [''], ["a", "b", "c"]
for n in digits: # n = 2, 3
letters = numtolet[n] # ["a", "b", "c"], ["d", "e", "f"]
current = [] # [], ["a", "b", "c"]
for r in result: # r = '', ["a", "b", "c"]
for l in letters: # l = 'a', l = 'd'
current.append(r+l) # ["a", "b", "c"] ["ad","ae","af","bd","be","bf","cd","ce","cf"]
result = current # ["a", "b", "c"], ["ad","ae","af","bd","be","bf","cd","ce","cf"]
return result
18. 4Sum
method: leetcode 15, 16 : 2 pointers
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
num_set = set()
nums.sort()
for i in range(len(nums) - 1):
for j in range(i + 1, len(nums)):
lo, hi = j + 1, len(nums) - 1
while lo < hi:
four = nums[i] + nums[j] + nums[lo] + nums[hi]
if four == target:
num_set.add((nums[i], nums[j], nums[lo], nums[hi]))
lo += 1
hi -= 1
elif four < target:
lo += 1
else:
hi -= 1
return num_set
19. Remove Nth Node From End of List
method: 2 pass
1 first pass count number of nodes
2 second pass remove node
Python:
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
p = q = dummy = ListNode(0)
dummy.next = head
counter = 0
while p:
counter += 1
p = p.next
k = counter - n
i = 1
while i < k:
q = q.next
i += 1
q.next = q.next.next
return dummy.next
JS:
// always forget new of ListNode()
var removeNthFromEnd = function(head, n) {
if (!head) return head
let dummy = new ListNode();
dummy.next = head;
let p = dummy;
let q = dummy;
// 1st pass
let count = 0;
while (p) {
count++;
p = p.next;
}
// 2nd pass
i = 1;
k = count - n;
while (i < k) {
i++;
q = q.next
}
q.next = q.next.next
return dummy.next
};
20. Valid Parentheses
method 1: replace, 没学数据结构前
class Solution:
def isValid(self, s: str) -> bool:
while "()" in s or "{}" in s or '[]' in s:
s = s.replace("()", "").replace('{}', "").replace('[]', "")
return s == ''
method 2: stack 学了数据结构
class Solution:
def isValid(self, s: str) -> bool:
stack = []
for c in s:
if c == '{' or c == '[' or c == '(':
stack.append(c)
elif stack and stack[-1] == '{' and c == '}':
stack.pop()
elif stack and stack[-1] == '[' and c == ']':
stack.pop()
elif stack and stack[-1] == '(' and c == ')':
stack.pop()
else:
return False
return len(stack) == 0