classSolution{public:boolcheckSubarraySum(vector<int>& nums,int k){if(!k){for(int i =1; i < nums.size(); i ++)if(!nums[i -1]&&!nums[i])returntrue;returnfalse;}int n = nums.size();
vector<int>s(n +1);for(int i =1; i <= n; i ++) s[i]= s[i -1]+ nums[i -1];
unordered_set<int> hash;for(int i =2; i <= n; i ++){
hash.insert(s[i -2]% k);if(hash.count(s[i]% k))returntrue;}returnfalse;}};
import java.util.HashMap;import java.util.Map;publicclassSolution{publicbooleancheckSubarraySum(int[] nums,int k){int sum =0;// key:区间 [0..i] 里所有元素的和 % k// value:下标 i
Map<Integer, Integer> map =newHashMap<>();// 理解初始化的意义
map.put(0,-1);int len = nums.length;for(int i =0; i < len; i++){
sum += nums[i];if(k !=0){
sum = sum % k;}if(map.containsKey(sum)){if(i - map.get(sum)>1){returntrue;}}else{
map.put(sum, i);}}returnfalse;}}
classSolution:defcheckSubarraySum(self, nums: List[int], k:int)->bool:iflen(nums)<2:returnFalse
dp, cur ={0:-1},0for idx, num inenumerate(nums):
cur += num
if k !=0: cur %= k
pre = dp.setdefault(cur, idx)if idx - pre >1:returnTruereturnFalse
funccheckSubarraySum(nums []int, k int)bool{iflen(nums)<2{returnfalse}for i :=0; i <len(nums)-1; i++{if nums[i]==0&& nums[i+1]==0{returntrue}}if k ==0{returnfalse}
m :=make(map[int]int)
m[0]=-1// 对于从头开始的数组,索引认为是-1,这样1--1=2
sum, h :=0,0for i :=0; i <len(nums); i++{
sum += nums[i]
h = sum % k
pre, ok := m[h]if!ok {
m[h]= i
}else{if i - pre >1{returntrue}}}returnfalse}
第五百二十四题:
classSolution{public:boolcheck(string& a, string& b){int i =0, j =0;while(i < a.size()&& j < b.size()){if(a[i]== b[j]) i ++;
j ++;}return i == a.size();}
string findLongestWord(string s, vector<string>& d){
string res;for(auto str: d)if(check(str, s)){if(res.empty()|| res.size()< str.size()|| res.size()== str.size()&& res > str)
res = str;}return res;}};
classSolution:deffindLongestWord(self, s:str, d: List[str])->str:'''
l = 0
longestword = []
a = 0
b = 0
for word in d:
a
if set(word).issubset(set(s)) and len(word) >= l:
if len(word) == l:
longestword = sorted([word,longestword])[0]
else:
longestword = word
l = len(word)
return longestword
'''# pythonic
d.sort(key =lambda x:[-len(x), x])#key = [-len(x), x] x指传入的参数deff(c):
i =0for letter in c:
k = s.find(letter, i)if k ==-1:returnFalse
i = k +1returnTruefor c in d:if f(c):return c
return''#双指针
d.sort(key =lambda x:[-len(x), x])for word in d:
a =0
b =0while a <len(s)and b <len(word):if s[a]== word[b]:
a +=1
b +=1else:
a +=1iflen(word)== b:return word
return''
funcfindLongestWord(s string, d []string)string{
r :=""iflen(s)<=0{return r
}for i :=range d {ifsubString(s, d[i]){iflen(d[i])>len(r)||(len(d[i])==len(r)&& d[i]< r ){
r = d[i]}}}return r
}// 此解法也可以做判断子序列的解法// https://leetcode-cn.com/problems/is-subsequence/ easyfuncsubString(s string, sub string)bool{iflen(sub)<=0{returntrue}
p1 :=0
p2 :=0for p1 <len(s){if s[p1]== sub[p2]{
p1++
p2++}else{
p1++}if p2 ==len(sub){returntrue}}returnfalse}
第五百二十五题:
classSolution{public:intfindMaxLength(vector<int>& nums){int n = nums.size();
unordered_map<int,int> hash;
hash[0]=0;int res =0;for(int i =1, one =0, zero =0; i <= n; i ++){int x = nums[i -1];if(x ==0) zero ++;else one ++;int s = one - zero;if(hash.count(s)) res =max(res, i - hash[s]);else hash[s]= i;}return res;}};
publicclassSolution{publicintfindMaxLength(int[] nums){
Map<Integer, Integer> map =newHashMap<>();
map.put(0,-1);int maxlen =0, count =0;for(int i =0; i < nums.length; i++){
count = count +(nums[i]==1?1:-1);if(map.containsKey(count)){
maxlen = Math.max(maxlen, i - map.get(count));}else{
map.put(count, i);}}return maxlen;}}
classSolution:deffindMaxLength(self, nums: List[int])->int:
dic ={0:-1}
count = res =0for i inrange(len(nums)):if nums[i]==0:
count -=1else:
count +=1if count in dic:
res =max(i-dic[count], res)else:
dic[count]= i
return res
funcfindMaxLength(nums []int)int{
cntIdx :=map[int]int{0:-1,}
cnt, maxLen :=0,0for i :=0; i <len(nums); i++{if nums[i]==0{
cnt +=-1}else{
cnt +=1}if v, ok := cntIdx[cnt]; ok {
maxLen =max(maxLen, i - v)}else{
cntIdx[cnt]= i
}}return maxLen
}funcmax(a, b int)int{if a < b {return b
}return a
}
第五百二十六题:
classSolution{public:intcountArrangement(int n){
vector<int>f(1<< n);
f[0]=1;for(int i =0; i <1<< n; i ++){int k =0;for(int j =0; j < n; j ++)if(i >> j &1)
k ++;for(int j =0; j < n; j ++)if(!(i >> j &1)){if((k +1)%(j +1)==0||(j +1)%(k +1)==0)
f[i |(1<< j)]+= f[i];}}return f[(1<< n)-1];}};
publicclassSolution{int count =0;publicintcountArrangement(int N){boolean[] visited =newboolean[N +1];calculate(N,1, visited);return count;}publicvoidcalculate(int N,int pos,boolean[] visited){if(pos > N)
count++;for(int i =1; i <= N; i++){if(!visited[i]&&(pos % i ==0|| i % pos ==0)){
visited[i]=true;calculate(N, pos +1, visited);
visited[i]=false;}}}}
classSolution:defcountArrangement(self, N:int)->int:
self.ans =0
visited =[0]*(N +1)defbacktrack(path):iflen(path)== N:
self.ans +=1returnfor i inrange(1, N +1):if visited[i]:continueif(len(path)+1)% i !=0and i %(len(path)+1)!=0:continue
path.append(i)
visited[i]=1
backtrack(path)
visited[i]=0
path.pop()
backtrack([])return self.ans
funccountArrangement(N int)int{var ans intvar backtrace func([]int,[]bool)
backtrace =func(path []int,vis []bool){iflen(path)== N {
ans++return}for v:=1;v<=N;v++{if i:=len(path); vis[v-1]|| v %(i+1)!=0&&(i+1)%v !=0{continue}
vis[v-1]=truebacktrace(append(path, v),vis)
vis[v-1]=false}}backtrace([]int{},make([]bool,N))return ans
}
第五百二十八题:
classSolution{public:
vector<int> s;Solution(vector<int>& w){
s = w;for(int i =1; i < s.size(); i ++) s[i]+= s[i -1];}intpickIndex(){int x =rand()% s.back()+1;returnlower_bound(s.begin(), s.end(), x)- s.begin();}};/**
* Your Solution object will be instantiated and called as such:
* Solution* obj = new Solution(w);
* int param_1 = obj->pickIndex();
*/
classSolution{
List<Integer> psum =newArrayList<>();int tot =0;
Random rand =newRandom();publicSolution(int[] w){for(int x : w){
tot += x;
psum.add(tot);}}publicintpickIndex(){int targ = rand.nextInt(tot);int lo =0;int hi = psum.size()-1;while(lo != hi){int mid =(lo + hi)/2;if(targ >= psum.get(mid)) lo = mid +1;else hi = mid;}return lo;}}
import random
classSolution:def__init__(self, w: List[int]):
self.w = w
self.leng =[0]*(len(w)+1)for i inrange(1,len(self.leng)):
self.leng[i]= self.leng[i-1]+ self.w[i-1]defpickIndex(self)->int:
d = random.randint(1,self.leng[-1])
l =1;r =len(self.leng)-1while l <= r:
mid =(l+r)>>1if self.leng[mid]>= d:
r = mid -1else:
l = mid +1
index = l -1return index
# Your Solution object will be instantiated and called as such:# obj = Solution(w)# param_1 = obj.pickIndex()
type Solution struct{
nums []int
sum int}funcConstructor(w []int) Solution {
sum :=0
weightSums :=make([]int,len(w))for i :=0; i <len(w); i++{
sum += w[i]
weightSums[i]= sum
}return Solution{weightSums, sum}}func(this *Solution)PickIndex()int{
target := rand.Intn(this.sum)
left, right :=0,len(this.nums)for left < right {
mid := left +(right - left)/2if target >= this.nums[mid]{
left = mid +1}elseif target < this.nums[mid]{
right = mid
}}return left
}
第五百二十九题:
classSolution{public:int n, m;
vector<vector<char>>updateBoard(vector<vector<char>>& board, vector<int>& click){
n = board.size(), m = board[0].size();int x = click[0], y = click[1];if(board[x][y]=='M'){
board[x][y]='X';return board;}dfs(board, x, y);return board;}voiddfs(vector<vector<char>>& board,int x,int y){if(board[x][y]!='E')return;int s =0;for(int i =max(x -1,0); i <=min(n -1, x +1); i ++)for(int j =max(y -1,0); j <=min(m -1, y +1); j ++)if(i != x || j != y)if(board[i][j]=='M'|| board[i][j]=='X')
s ++;if(s){
board[x][y]='0'+ s;return;}
board[x][y]='B';for(int i =max(x -1,0); i <=min(n -1, x +1); i ++)for(int j =max(y -1,0); j <=min(m -1, y +1); j ++)if(i != x || j != y)dfs(board, i, j);}};
classSolution{int[] dirX ={0,1,0,-1,1,1,-1,-1};int[] dirY ={1,0,-1,0,1,-1,1,-1};publicchar[][]updateBoard(char[][] board,int[] click){int x = click[0], y = click[1];if(board[x][y]=='M'){// 规则 1
board[x][y]='X';}else{bfs(board, x, y);}return board;}publicvoidbfs(char[][] board,int sx,int sy){
Queue<int[]> queue =newLinkedList<int[]>();boolean[][] vis =newboolean[board.length][board[0].length];
queue.offer(newint[]{sx, sy});
vis[sx][sy]=true;while(!queue.isEmpty()){int[] pos = queue.poll();int cnt =0, x = pos[0], y = pos[1];for(int i =0; i <8;++i){int tx = x + dirX[i];int ty = y + dirY[i];if(tx <0|| tx >= board.length || ty <0|| ty >= board[0].length){continue;}// 不用判断 M,因为如果有 M 的话游戏已经结束了if(board[tx][ty]=='M'){++cnt;}}if(cnt >0){// 规则 3
board[x][y]=(char)(cnt +'0');}else{// 规则 2
board[x][y]='B';for(int i =0; i <8;++i){int tx = x + dirX[i];int ty = y + dirY[i];// 这里不需要在存在 B 的时候继续扩展,因为 B 之前被点击的时候已经被扩展过了if(tx <0|| tx >= board.length || ty <0|| ty >= board[0].length || board[tx][ty]!='E'|| vis[tx][ty]){continue;}
queue.offer(newint[]{tx, ty});
vis[tx][ty]=true;}}}}}
classSolution:defupdateBoard(self, board: List[List[str]], click: List[int])-> List[List[str]]:
direction =((1,0),(-1,0),(0,1),(0,-1),(1,1),(-1,1),(-1,-1),(1,-1))if board[click[0]][click[1]]=='M':
board[click[0]][click[1]]='X'return board
self.m,self.n =len(board),len(board[0])defcheck(i, j):
cnt =0for x,y in direction:
x, y = x + i, y + j
if0<= x < self.m and0<= y < self.n and board[x][y]=='M':
cnt +=1return cnt
defdfs(i, j):
cnt = check(i, j)ifnot cnt:
board[i][j]='B'for x, y in direction:
x, y = x + i, y + j
if0<= x < self.m and0<= y < self.n and board[x][y]=='E': dfs(x, y)else: board[i][j]=str(cnt)
dfs(click[0],click[1])return board
var dirX =[]int{0,1,0,-1,1,1,-1,-1}var dirY =[]int{1,0,-1,0,1,-1,1,-1}funcupdateBoard(board [][]byte, click []int)[][]byte{
x, y := click[0], click[1]if board[x][y]=='M'{
board[x][y]='X'}else{bfs(board, x, y)}return board
}funcbfs(board [][]byte, sx, sy int){
queue :=[][]int{}
vis :=make([][]bool,len(board))for i :=0; i <len(vis); i++{
vis[i]=make([]bool,len(board[0]))}
queue =append(queue,[]int{sx, sy})
vis[sx][sy]=truefor i :=0; i <len(queue); i++{
cnt, x, y :=0, queue[i][0], queue[i][1]for i :=0; i <8; i++{
tx, ty := x + dirX[i], y + dirY[i]if tx <0|| tx >=len(board)|| ty <0|| ty >=len(board[0]){continue}// 不用判断 M,因为如果有 M 的话游戏已经结束了if board[tx][ty]=='M'{
cnt++}}if cnt >0{
board[x][y]=byte(cnt +'0')}else{
board[x][y]='B'for i :=0; i <8; i++{
tx, ty := x + dirX[i], y + dirY[i]// 这里不需要在存在 B 的时候继续扩展,因为 B 之前被点击的时候已经被扩展过了if tx <0|| tx >=len(board)|| ty <0|| ty >=len(board[0])|| board[tx][ty]!='E'|| vis[tx][ty]{continue}
queue =append(queue,[]int{tx, ty})
vis[tx][ty]=true}}}}
第五百三十题:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/classSolution{public:int ans = INT_MAX, last;bool is_first =true;intgetMinimumDifference(TreeNode* root){dfs(root);return ans;}voiddfs(TreeNode* root){if(!root)return;dfs(root->left);if(is_first) is_first =false;else ans =min(ans, root->val - last);
last = root->val;dfs(root->right);}};
classSolution{int pre;int ans;publicintgetMinimumDifference(TreeNode root){
ans = Integer.MAX_VALUE;
pre =-1;dfs(root);return ans;}publicvoiddfs(TreeNode root){if(root == null){return;}dfs(root.left);if(pre ==-1){
pre = root.val;}else{
ans = Math.min(ans, root.val - pre);
pre = root.val;}dfs(root.right);}}
# Definition for a binary tree node.# class TreeNode:# def __init__(self, x):# self.val = x# self.left = None# self.right = NoneclassSolution:defgetMinimumDifference(self, root: TreeNode)->int:#初始化,最小值赋值为无穷大,last_value记录上一个节点的值
min_value, last_value =float("inf"),-1defpengding_num(val):nonlocal min_value, last_value
#第一个节点赋值给last_valueif last_value ==-1:
last_value = val
else:#每次求差的绝对值的最小值,更新
min_value =min(min_value,abs(val - last_value))
last_value = val
#中序遍历defmid_order(root):nonlocal min_value, last_value
if root:
mid_order(root.left)#处理当前节点
pengding_num(root.val)
mid_order(root.right)
mid_order(root)return min_value
funcgetMinimumDifference(root *TreeNode)int{
ans, pre := math.MaxInt64,-1var dfs func(*TreeNode)
dfs =func(node *TreeNode){if node ==nil{return}dfs(node.Left)if pre !=-1&& node.Val-pre < ans {
ans = node.Val - pre
}
pre = node.Val
dfs(node.Right)}dfs(root)return ans
}