这几天懒得排版、格式随意,勿怪
1. Largest Time for Given Digits
def largestTimeFromDigits(self, A: List[int]) -> str:
max_time = -1
#枚举enumerate 所有可能性
for h, i, j, k in itertools.permutations(A):
Hour = h*10 + i
Minute = j*10 + k
if Hour < 24 and Minute < 60:
max_time = max(max_time, Hour * 60 + Minute)
if max_time == -1:
return "" #Leetcode特色,给空的输入。。
else:
return "{:02d}:{:02d}".format(max_time // 60, max_time % 60)
c++版
public:
string largestTimeFromDigits(vector<int>& A) {
sort(begin(A), end(A), greater<int>());
do if ((A[0] < 2 || (A[0] == 2 && A[1] < 4)) && A[2] < 6)
return to_string(A[0]) + to_string(A[1]) + ":" + to_string(A[2]) + to_string(A[3]);
while (prev_permutation(begin(A), end(A)));
return "";
}
2. 220. Contains Duplicate III
def containsNearbyAlmostDuplicate(self, nums: List[int], k: int, t: int) -> bool:
if t < 0: return False
n = len(nums)
d = {} #开字典dict
w = t + 1
for i in range(n):
m = nums[i] // w
if m in d:
return True
if m - 1 in d and abs(nums[i] - d[m - 1]) < w:
return True
if m + 1 in d and abs(nums[i] - d[m + 1]) < w:
return True
d[m] = nums[i]
if i >= k:
del d[nums[i - k] // w]
return False
[3. Repeated Substring Pattern]
[4. Partition Labels] 贪心
class Solution:
def partitionLabels(self, S: str) -> List[int]:
rightmost = {c:i for i, c in enumerate(S)}
left, right = 0, 0
result = []
for i, letter in enumerate(S):
right = max(right,rightmost[letter])
if i == right:
result += [right-left + 1]
left = i+1
return result
[5. All Elements in Two Binary Search Trees]
用了sort() 排序, 如果不用排序详见评论区
def getAllElements(self, root1: TreeNode, root2: TreeNode) -> List[int]:
def inorder(node: TreeNode) -> None:
if not node:
return
inorder(node.left)
ans.append(node.val)
inorder(node.right)
ans = []
inorder(root1)
inorder(root2)
return sorted(ans)
[6. Image Overlap]
DP
def largestOverlap(self, A: List[List[int]], B: List[List[int]]) -> int:
N = len(A)
LA = [i // N * 100 + i % N for i in range(N * N) if A[i // N][i % N]]
LB = [i // N * 100 + i % N for i in range(N * N) if B[i // N][i % N]]
c = collections.Counter(i - j for i in LA for j in LB)
return max(c.values() or [0])
[7. Word Pattern]
def wordPattern(self, pattern: str, str: str) -> bool:
str=str.split()
return map(pattern.index,pattern)==map(str.index,str)
或者c++
class Solution {
public:
bool wordPattern(string pattern, string str) {
map<char, int> p2i;
map<string, int> w2i;
istringstream in(str);
int i = 0, n = pattern.size();
for (string word; in >> word; ++i) {
if (i == n || p2i[pattern[i]] != w2i[word])
return false;
p2i[pattern[i]] = w2i[word] = i + 1;
}
return i == n;
}
};
[8. Sum of Root To Leaf Binary Numbers]
def sumRootToLeaf(self, root: TreeNode) -> int:
stack = [[root, ""]] # iteration to keep track
result = 0 # result holder
# 通过放入栈来遍历(这个树的)节点
while stack:
# 当前节点,路径
current, path = stack.pop(0)
# 遍历 ,含路径信息
if current.left:
stack.append([current.left, path+str(current.val)])
if current.right:
stack.append([current.right, path+str(current.val)])
# leaf node condition when we update result
if not current.left and not current.right:
path += str(current.val)
result += int(path, 2)
return result
[9. Compare Version Numbers版本号对比]
#字符串读取比较
s1 = [int(i) for i in version1.split(".")]
s2 = [int(i) for i in version2.split(".")]
l1, l2 = len(s1), len(s2)
if l1 < l2: s1 += [0]*(l2-l1)
else: s2 += [0]*(l1 - l2)
return (s1 > s2) - (s1 < s2)
v1, v2 = map(int, v1.split('.')), map(int, v2.split('.'))
v1, v2 = zip(*zip_longest(v1, v2, fillvalue = 0))
return (0, 1, -1)[(v1 > v2) - (v1 < v2)]
from itertools import zip_longest
versions1 = list(map(int, version1.split(".")))
versions2 = list(map(int, version2.split(".")))
for v1, v2 in zip_longest(versions1, versions2, fillvalue=0):
if v1 > v2:
return 1
elif v1 < v2:
return -1
return 0
versions1 = [int(v) for v in version1.split(".")]
versions2 = [int(v) for v in version2.split(".")]
for i in range(max(len(versions1),len(versions2))):
v1 = versions1[i] if i < len(versions1) else 0
v2 = versions2[i] if i < len(versions2) else 0
if v1 > v2:
return 1
elif v1 < v2:
return -1;
return 0;
"""
[10. Bulls and Cows]
def getHint(self, secret: str, guess: str) -> str:
A = sum(a==b for a,b in zip(secret, guess))
B = collections.Counter(secret) & collections.Counter(guess)
return "%dA%dB" % (A, sum(B.values()) - A)
[11. Maximum Product Subarray]
def maxProduct(self, A: List[int]) -> int:
B = A[::-1]
for i in range(1, len(A)):
A[i] *= A[i - 1] or 1
B[i] *= B[i - 1] or 1
return max(A + B)
[12. Combination Sum III]
DFS
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
ret = []
self.dfs(list(range(1, 10)), k, n, [], ret)
return ret
def dfs(self, nums, k, n, path, ret):
if k < 0 or n < 0:
return
if k == 0 and n == 0:
ret.append(path)
for i in range(len(nums)):
self.dfs(nums[i+1:], k-1, n-nums[i], path+[nums[i]], ret)
[13. Insert Interval] 插入区间
def insert(self, a: List[List[int]], b: List[int]) -> List[List[int]]:
res = []
k = 0
while (k < len(a) and a[k][1] < b[0]):
res.append(a[k])
k+=1
if k< len(a):
b[0] = min(b[0], a[k][0]);
while (k < len(a) and a[k][0] <= b[1]):
b[1] = max(b[1], a[k][1])
k += 1
res.append(b)
while (k < len(a)):
res.append(a[k])
k += 1
return res
[14. House Robber]
DP
def rob(self, nums: List[int]) -> int:
last, now = 0, 0
for i in nums: last, now = now, max(last + i, now)
return now
[15. Length of Last Word]
def lengthOfLastWord(self, s: str) -> int:
count=0
for letter in s.rstrip(" ")[::-1]:
if letter==" ":
break
count+=1
return count
c++
int lengthOfLastWord(string s) {
int len = 0, tail = s.length() - 1;
while (tail >= 0 && s[tail] == ' ') tail--;
while (tail >= 0 && s[tail] != ' ') {
len++;
tail--;
}
return len;
}
[16. Maximum XOR of Two Numbers in an Array]
Trie树
class Solution {
struct treenode {
treenode* left, *right;
treenode():left(NULL), right(NULL) {}
};
public:
int findMaximumXOR(vector<int>& nums) {
treenode* root = new treenode();
int ans = 0;
// build a trie and get the max xor value on the fly for the current trie
for (int num:nums) ans = max(ans, build(root, num));
return ans;
}
private:
int build(treenode* p, int num) {
int ans = 0, mask = 1<<30;
treenode* q = p;
for (int i = 30; i >= 0; i--) {
ans <<= 1;
if (num&mask) {
//build a trie
if (p->right == NULL) p->right = new treenode();
p = p->right;
//get xor value on the fly
if (q->left) {
ans++;
q = q->left;
}
else
q = q->right;
}
else {
if (p->left == NULL) p->left = new treenode();
p = p->left;
if (q->right) {
ans++;
q = q->right;
}
else
q = q->left;
}
mask >>= 1;
}
return ans;
}
};
python异或做法
def findMaximumXOR(self, nums: List[int]) -> int:
ans = 0
for i in reversed(range(32)):
prefixes = set([x >> i for x in nums])
ans <<=1
candidate = ans + 1
for p in prefixes:
if candidate ^ p in prefixes:
ans = candidate
break
return ans