classSolution{public:
vector<int>findDisappearedNumbers(vector<int>& nums){for(auto x: nums){
x =abs(x);if(nums[x -1]>0) nums[x -1]*=-1;}
vector<int> res;for(int i =0; i < nums.size(); i ++)if(nums[i]>0)
res.push_back(i +1);return res;}};
classSolution{public List<Integer>findDisappearedNumbers(int[] nums){int n = nums.length;for(int num : nums){int x =(num -1)% n;
nums[x]+= n;}
List<Integer> ret =newArrayList<Integer>();for(int i =0; i < n; i++){if(nums[i]<= n){
ret.add(i +1);}}return ret;}}
classSolution:deffindDisappearedNumbers(self, nums: List[int])-> List[int]:
n =len(nums)for num in nums:
x =(num -1)% n
nums[x]+= n
ret =[i +1for i, num inenumerate(nums)if num <= n]return ret
funcfindDisappearedNumbers(nums []int)(ans []int){
n :=len(nums)for_, v :=range nums {
v =(v -1)% n
nums[v]+= n
}for i, v :=range nums {if v <= n {
ans =append(ans, i+1)}}return}
第四百四十九题:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/classCodec{public:// Encodes a tree to a single string.
string serialize(TreeNode* root){
string res;dfs_s(root, res);return res;}voiddfs_s(TreeNode* root, string& res){if(!root)return;
res +=to_string(root->val)+' ';dfs_s(root->left, res),dfs_s(root->right, res);}// Decodes your encoded data to tree.
TreeNode*deserialize(string str){
vector<int> data;
stringstream ssin(str);int x, u =0;while(ssin >> x) data.push_back(x);returndfs_d(data, u, INT_MIN, INT_MAX);}
TreeNode*dfs_d(vector<int>& data,int& u,int minv,int maxv){if(u == data.size()|| data[u]< minv || data[u]> maxv)returnNULL;auto root =newTreeNode(data[u ++]);
root->left =dfs_d(data, u, minv, root->val);
root->right =dfs_d(data, u, root->val +1, maxv);return root;}};// Your Codec object will be instantiated and called as such:// Codec* ser = new Codec();// Codec* deser = new Codec();// string tree = ser->serialize(root);// TreeNode* ans = deser->deserialize(tree);// return ans;
publicclassCodec{// Encodes a tree to a list.publicvoidpostorder(TreeNode root, StringBuilder sb){if(root == null)return;postorder(root.left, sb);postorder(root.right, sb);
sb.append(intToString(root.val));}// Encodes integer to bytes stringpublic String intToString(int x){char[] bytes =newchar[4];for(int i =3; i >-1;--i){
bytes[3- i]=(char)(x >>(i *8)&0xff);}returnnewString(bytes);}// Encodes a tree to a single string.public String serialize(TreeNode root){
StringBuilder sb =newStringBuilder();postorder(root, sb);return sb.toString();}// Decodes list to tree.public TreeNode helper(Integer lower, Integer upper, ArrayDeque<Integer> nums){if(nums.isEmpty())return null;int val = nums.getLast();if(val < lower || val > upper)return null;
nums.removeLast();
TreeNode root =newTreeNode(val);
root.right =helper(val, upper, nums);
root.left =helper(lower, val, nums);return root;}// Decodes bytes string to integerpublicintstringToInt(String bytesStr){int result =0;for(char b : bytesStr.toCharArray()){
result =(result <<8)+(int)b;}return result;}// Decodes your encoded data to tree.public TreeNode deserialize(String data){
ArrayDeque<Integer> nums =newArrayDeque<Integer>();int n = data.length();for(int i =0; i <(int)(n /4);++i){
nums.add(stringToInt(data.substring(4* i,4* i +4)));}returnhelper(Integer.MIN_VALUE, Integer.MAX_VALUE, nums);}}
classCodec:defpostorder(self, root):return self.postorder(root.left)+ self.postorder(root.right)+[root.val]if root else[]defint_to_str(self, x):"""
Encodes integer to bytes string
"""bytes=[chr(x >>(i *8)&0xff)for i inrange(4)]bytes.reverse()
bytes_str =''.join(bytes)return bytes_str
defserialize(self, root):"""
Encodes a tree to a single string.
"""
lst =[self.int_to_str(x)for x in self.postorder(root)]return''.join(map(str, lst))defstr_to_int(self, bytes_str):"""
Decodes bytes string to integer.
"""
result =0for ch in bytes_str:
result = result *256+ord(ch)return result
defdeserialize(self, data):"""
Decodes your encoded data to tree.
"""defhelper(lower =float('-inf'), upper =float('inf')):ifnot data or data[-1]< lower or data[-1]> upper:returnNone
val = data.pop()
root = TreeNode(val)
root.right = helper(val, upper)
root.left = helper(lower, val)return root
n =len(data)# split data string into chunks of 4 bytes# and convert each chunk to int
data =[self.str_to_int(data[4* i :4* i +4])for i inrange(n //4)]return helper()
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/type Codec struct{}funcConstructor() Codec {return Codec{}}// Serializes a tree to a single string.func(this *Codec)serialize(root *TreeNode)string{if root==nil{return"#"}return strconv.Itoa(root.Val)+","+this.serialize(root.Left)+","+this.serialize(root.Right)}funcdfs(strs *[]string)*TreeNode{
tmp:=(*strs)[0]*strs =(*strs)[1:]if tmp=="#"{returnnil}
value,_:=strconv.Atoi(tmp)
root:=&TreeNode{Val:value}
root.Left =dfs(strs)
root.Right =dfs(strs)return root
}// Deserializes your encoded data to tree.func(this *Codec)deserialize(data string)*TreeNode {
strs:=strings.Split(data,",")returndfs(&strs)}/**
* Your Codec object will be instantiated and called as such:
* obj := Constructor();
* data := obj.serialize(root);
* ans := obj.deserialize(data);
*/
classSolution{/*
One step right and then always left
*/publicintsuccessor(TreeNode root){
root = root.right;while(root.left != null) root = root.left;return root.val;}/*
One step left and then always right
*/publicintpredecessor(TreeNode root){
root = root.left;while(root.right != null) root = root.right;return root.val;}public TreeNode deleteNode(TreeNode root,int key){if(root == null)return null;// delete from the right subtreeif(key > root.val) root.right =deleteNode(root.right, key);// delete from the left subtreeelseif(key < root.val) root.left =deleteNode(root.left, key);// delete the current nodeelse{// the node is a leafif(root.left == null && root.right == null) root = null;// the node is not a leaf and has a right childelseif(root.right != null){
root.val =successor(root);
root.right =deleteNode(root.right, root.val);}// the node is not a leaf, has no right child, and has a left child else{
root.val =predecessor(root);
root.left =deleteNode(root.left, root.val);}}return root;}}
classSolution:defsuccessor(self, root):"""
One step right and then always left
"""
root = root.right
while root.left:
root = root.left
return root.val
defpredecessor(self, root):"""
One step left and then always right
"""
root = root.left
while root.right:
root = root.right
return root.val
defdeleteNode(self, root: TreeNode, key:int)-> TreeNode:ifnot root:returnNone# delete from the right subtreeif key > root.val:
root.right = self.deleteNode(root.right, key)# delete from the left subtreeelif key < root.val:
root.left = self.deleteNode(root.left, key)# delete the current nodeelse:# the node is a leafifnot(root.left or root.right):
root =None# the node is not a leaf and has a right childelif 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
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/funcdeleteNode(root *TreeNode, key int)*TreeNode {if root ==nil{returnnil}if key < root.Val {
root.Left =deleteNode(root.Left, key)}elseif root.Val < key {
root.Right =deleteNode(root.Right, key)}else{if root.Left ==nil{return root.Right
}if root.Right ==nil{return root.Left
}
min := root.Right
for min.Left !=nil{
min = min.Left
}
min.Left = root.Left
root = root.Right
}return root
}
classSolution:deffrequencySort(self, s:str)->str:# Counterreturn''.join([i * j for i, j in collections.Counter(s).most_common()])
funcfrequencySort(s string)string{
m :=make(map[rune]int)
ret :=make([]rune,0)//存放每一个字符
res :=make([]rune,0)//存放结果//注意!!要将s转成rune 因为使用for i,v:=range s的时候,这个v是rune的 最后return再转回来即可
r :=[]rune(s)//这个for循环是得到string中每一个字符的频率,用一个数组存下字符for_,v :=range r {//判断m这个map里面有没有v这个Key
i,ok := m[v]if ok {//如果有的话则将m[v]的value+1
m[v]= i+1// 即m[v]++}else{
m[v]=1
ret =append(ret, v)}}//按照频率的大小排序
sort.Slice(ret,func(i, j int)bool{return m[ret[i]]> m[ret[j]]})//按照频率将每个字符复原成字符串for i:=0;i<len(ret);i++{for j:=0;j<m[ret[i]];j++{
res=append(res,ret[i])}}returnstring(res)}
第四百五十二题:
classSolution{public:intfindMinArrowShots(vector<vector<int>>& points){if(points.empty())return0;sort(points.begin(), points.end(),[](vector<int> a, vector<int> b){return a[1]< b[1];});int res =1, r = points[0][1];for(int i =1; i < points.size(); i ++)if(points[i][0]> r){
res ++;
r = points[i][1];}return res;}};
funcminMoves(nums []int)int{
min := nums[0]for i :=1;i <len(nums);i++{if nums[i]< min {
min = nums[i]}}
res :=0for i :=0;i <len(nums);i++{
res += nums[i]- min
}return res
}
第四百五十四题:
classSolution{public:intfourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D){
unordered_map<int,int> cnt;for(auto c: C)for(auto d: D)
cnt[c + d]++;int res =0;for(auto a: A)for(auto b: B)
res += cnt[-(a + b)];return res;}};
classSolution{publicintfourSumCount(int[] A,int[] B,int[] C,int[] D){
Map<Integer, Integer> countAB =newHashMap<Integer, Integer>();for(int u : A){for(int v : B){
countAB.put(u + v, countAB.getOrDefault(u + v,0)+1);}}int ans =0;for(int u : C){for(int v : D){if(countAB.containsKey(-u - v)){
ans += countAB.get(-u - v);}}}return ans;}}
classSolution:deffourSumCount(self, A: List[int], B: List[int], C: List[int], D: List[int])->int:
countAB = collections.Counter(u + v for u in A for v in B)
ans =0for u in C:for v in D:if-u - v in countAB:
ans += countAB[-u - v]return ans
funcfourSumCount(a, b, c, d []int)(ans int){
countAB :=map[int]int{}for_, v :=range a {for_, w :=range b {
countAB[v+w]++}}for_, v :=range c {for_, w :=range d {
ans += countAB[-v-w]}}return}