classAllOne{public:struct Node {
Node *left,*right;int val;
unordered_set<string> S;
Node (int _val){
val = _val;
left = right =NULL;}}*left,*right;
unordered_map<string, Node*> hash;/** Initialize your data structure here. */AllOne(){
left =newNode(INT_MIN), right =newNode(INT_MAX);
left->right = right, right->left = left;}
Node*add_to_right(Node* node, string key,int val){if(node->right->val == val) node->right->S.insert(key);else{auto t =newNode(val);
t->S.insert(key);
t->right = node->right, node->right->left = t;
node->right = t, t->left = node;}return node->right;}
Node*add_to_left(Node* node, string key,int val){if(node->left->val == val) node->left->S.insert(key);else{auto t =newNode(val);
t->S.insert(key);
t->left = node->left, node->left->right = t;
node->left = t, t->right = node;}return node->left;}voidremove(Node* node){
node->left->right = node->right;
node->right->left = node->left;delete node;}/** Inserts a new key <Key> with value 1. Or increments an existing key by 1. */voidinc(string key){if(hash.count(key)==0) hash[key]=add_to_right(left, key,1);else{auto t = hash[key];
t->S.erase(key);
hash[key]=add_to_right(t, key, t->val +1);if(t->S.empty())remove(t);}}/** Decrements an existing key by 1. If Key's value is 1, remove it from the data structure. */voiddec(string key){if(hash.count(key)==0)return;auto t = hash[key];
t->S.erase(key);if(t->val >1){
hash[key]=add_to_left(t, key, t->val -1);}else{
hash.erase(key);}if(t->S.empty())remove(t);}/** Returns one of the keys with maximal value. */
string getMaxKey(){if(right->left != left)return*right->left->S.begin();return"";}/** Returns one of the keys with Minimal value. */
string getMinKey(){if(left->right != right)return*left->right->S.begin();return"";}};/**
* Your AllOne object will be instantiated and called as such:
* AllOne* obj = new AllOne();
* obj->inc(key);
* obj->dec(key);
* string param_3 = obj->getMaxKey();
* string param_4 = obj->getMinKey();
*/
classKeyNode:def__init__(self, key):
self.key = key
self.prev =None
self.next=NoneclassKeyList:def__init__(self):
self.keyNode ={}
self.keyHead = KeyNode("")
self.keyTail = KeyNode("")
self.keyHead.next= self.keyTail
self.keyTail.prev = self.keyHead
defisEmpty(self):returnnot self.keyNode
defadd(self, key):
newNode = KeyNode(key)
newNode.prev, newNode.next= self.keyHead, self.keyHead.next
self.keyHead.next.prev = newNode
self.keyHead.next= newNode
self.keyNode[key]= newNode
defremove(self, key):
delNode = self.keyNode[key]
delNode.prev.next, delNode.next.prev = delNode.next, delNode.prev
del self.keyNode[key]classCountNode:def__init__(self, count):
self.count = count
self.keyList = KeyList()
self.prev =None
self.next=NonedefisEmpty(self):return self.keyList.isEmpty()defadd(self, key):
self.keyList.add(key)defremove(self, key):
self.keyList.remove(key)defgetKey(self):return self.keyList.keyHead.next.key
classCountList:def__init__(self):
self.keyCountNode ={}
self.countHead = CountNode(-1)
self.countTail = CountNode(-1)
self.countHead.next= self.countTail
self.countTail.prev = self.countHead
defisEmpty(self):returnnot self.keyCountNode
defadd(self, key):if key notin self.keyCountNode:if self.countHead.next.count ==1:
self.countHead.next.add(key)else:
oneCount = CountNode(1)
oneCount.add(key)
oneCount.prev, oneCount.next= self.countHead, self.countHead.next
self.countHead.next.prev, self.countHead.next= oneCount, oneCount
self.keyCountNode[key]= self.countHead.nextelse:
countNode = self.keyCountNode[key]
moreCount = countNode.count +1if countNode.next.count == moreCount:
countNode.next.add(key)
self.keyCountNode[key]= countNode.nextelse:
newNode = CountNode(moreCount)
newNode.add(key)
newNode.prev, newNode.next= countNode, countNode.next
countNode.next.prev, countNode.next= newNode, newNode
self.keyCountNode[key]= newNode
countNode.remove(key)if countNode.isEmpty():
countNode.prev.next, countNode.next.prev = countNode.next, countNode.prev
defremove(self, key):
countNode = self.keyCountNode[key]
lessCount = countNode.count -1if countNode.prev.count == lessCount:
countNode.prev.add(key)
self.keyCountNode[key]= countNode.prev
elif lessCount !=0:
newNode = CountNode(lessCount)
newNode.add(key)
newNode.prev, newNode.next= countNode.prev, countNode
countNode.prev.next, countNode.prev = newNode, newNode
self.keyCountNode[key]= newNode
else:del self.keyCountNode[key]
countNode.remove(key)if countNode.isEmpty():
countNode.prev.next, countNode.next.prev = countNode.next, countNode.prev
classAllOne:def__init__(self):"""
Initialize your data structure here.
"""
self.countList = CountList()definc(self, key:str)->None:"""
Inserts a new key <Key> with value 1. Or increments an existing key by 1.
"""
self.countList.add(key)defdec(self, key:str)->None:"""
Decrements an existing key by 1. If Key's value is 1, remove it from the data structure.
"""if key notin self.countList.keyCountNode:return
self.countList.remove(key)defgetMaxKey(self)->str:"""
Returns one of the keys with maximal value.
"""if self.countList.isEmpty():return""return self.countList.countTail.prev.getKey()defgetMinKey(self)->str:"""
Returns one of the keys with Minimal value.
"""if self.countList.isEmpty():return""return self.countList.countHead.next.getKey()
type AllOne struct{
H map[string]*DoubleListNode
DList DoubleList
}type DoubleListNode struct{
key string
val int
prev *DoubleListNode
next *DoubleListNode
}type DoubleList struct{
head *DoubleListNode
tail *DoubleListNode
length int}/** Initialize your data structure here. */funcConstructor() AllOne {//head、tail节点不存具体的数据
head :=&DoubleListNode{
key:"",
val:0,}
tail :=&DoubleListNode{
key:"",
val:0,}
head.next = tail
tail.prev = head
return AllOne{
H:make(map[string]*DoubleListNode),
DList: DoubleList{
head: head,
tail: tail,
length:0,},}}/** Inserts a new key <Key> with value 1. Or increments an existing key by 1. */func(this *AllOne)Inc(key string){if node, ok := this.H[key]; ok {//key存在直接加1 需要维护链表有序
node.val++
cur := node.next
for cur != this.DList.tail {if cur.val >= node.val {//寻找下一个大于等于node的节点 将node移动到该节点前边break}
cur = cur.next
}if node.next != cur {
this.RemoveNode(node)
this.InsertNode(node, cur)}}else{//key不存在 生成节点插在head节点后
node :=&DoubleListNode{
key: key,
val:1,}
node.next = this.DList.head.next
node.prev = this.DList.head
this.DList.head.next.prev = node
this.DList.head.next = node
this.H[key]= node
this.DList.length++}}//删除节点func(this *AllOne)RemoveNode(node *DoubleListNode){
node.prev.next = node.next
node.next.prev = node.prev
}//在cur节点前插入node节点func(this *AllOne)InsertNode(node, cur *DoubleListNode){
node.next = cur
node.prev = cur.prev
cur.prev.next = node
cur.prev = node
}/** Decrements an existing key by 1. If Key's value is 1, remove it from the data structure. */func(this *AllOne)Dec(key string){if node, ok := this.H[key]; ok {//key存在 key不存在不需处理if node.val <=1{//删除节点
this.RemoveNode(node)
this.DList.length--delete(this.H, key)}else{//节点减1 需要维护链表有序
node.val--
cur := node.prev
for cur != this.DList.tail {if cur.val <= node.val {//寻找上一个小于等于node的节点 将node移动到该节点前边break}
cur = cur.prev
}if node.prev != cur {
this.RemoveNode(node)
this.InsertNode(node, cur)}}}}/** Returns one of the keys with maximal value. */func(this *AllOne)GetMaxKey()string{if this.DList.length ==0{return""}return this.DList.tail.prev.key
}/** Returns one of the keys with Minimal value. */func(this *AllOne)GetMinKey()string{if this.DList.length ==0{return""}return this.DList.head.next.key
}
第四百三十三题:
classSolution{public:intminMutation(string start, string end, vector<string>& bank){
unordered_set<string> S;for(auto& s: bank) S.insert(s);
unordered_map<string,int> dist;
queue<string> q;
q.push(start);
dist[start]=0;char chrs[4]={'A','T','C','G'};while(q.size()){auto t = q.front();
q.pop();for(int i =0; i < t.size(); i ++){auto s = t;for(char c: chrs){
s[i]= c;if(S.count(s)&& dist.count(s)==0){
dist[s]= dist[t]+1;if(s == end)return dist[s];
q.push(s);}}}}return-1;}};
defminMutation(self, start:str, end:str, bank: List[str])->int:
bank =set(bank)if end notin bank:return-1
change_map ={"A":"CGT","C":"AGT","G":"CAT","T":"CGA",}
min_count =len(bank)+1defdfs(current, count, current_bank):nonlocal min_count
# terminatorif count > min_count:returnif current == end:if count < min_count:
min_count = count
returnifnot current_bank:return# processfor i, s inenumerate(current):for char in change_map[s]:
new = current[:i]+ char + current[i +1:]if new notin current_bank:continue
current_bank.remove(new)# drill down
dfs(new, count +1, current_bank)# reverse state
current_bank.add(new)
dfs(start,0, bank)return min_count if min_count <=len(bank)else-1
funcminMutation(start string, end string, bank []string)int{
result :=make([]int,0)dfs(start, end, bank,make([]bool,len(bank),len(bank)),0,&result)
sort.Ints(result)// 从小到达排序,取出最小的值就是最优解。iflen(result)==0{// 如果result的长度等于0,证明dfs中并没有对result进行拼接,就是start无法通过bank变成endreturn-1}return result[0]}// dfsfuncdfs(temp string, end string, bank []string, bankVisted []bool, level int, result *[]int){// 结束条件if temp == end {*result =append(*result, level)return}// 本层处理for i :=0; i <len(bank); i++{if!bankVisted[i]&&checkDifference(temp, bank[i]){// 未visited&&相差一个字母
bankVisted[i]=true// 标记为已读dfs(bank[i], end, bank, bankVisted, level+1, result)// 继续递归
bankVisted[i]=false// 回溯,标记位未读}}}// 比较是否相差一个字母funccheckDifference(temp string, bankByOne string)bool{
diff :=0for i :=0; i <len(temp); i++{if temp[i]!=bankByOne[i]{
diff++}}if diff ==1{returntrue}returnfalse}
第四百三十四题:
classSolution{public:intcountSegments(string s){int res =0;for(int i =0; i < s.size(); i ++){if(s[i]==' ')continue;int j = i +1;while(j < s.size()&& s[j]!=' ') j ++;
res ++;
i = j -1;}return res;}};
classSolution{public:interaseOverlapIntervals(vector<vector<int>>& q){sort(q.begin(), q.end(),[](vector<int> a, vector<int> b){return a[1]< b[1];});if(q.empty())return0;int res =1, r = q[0][1];for(int i =1; i < q.size(); i ++)if(q[i][0]>= r){
res ++;
r = q[i][1];}return q.size()- res;}};
classSolution{publicinteraseOverlapIntervals(int[][] intervals){if(intervals.length ==0){return0;}
Arrays.sort(intervals,newComparator<int[]>(){publicintcompare(int[] interval1,int[] interval2){return interval1[0]- interval2[0];}});int n = intervals.length;int[] f =newint[n];
Arrays.fill(f,1);for(int i =1; i < n;++i){for(int j =0; j < i;++j){if(intervals[j][1]<= intervals[i][0]){
f[i]= Math.max(f[i], f[j]+1);}}}return n - Arrays.stream(f).max().getAsInt();}}
classSolution:deferaseOverlapIntervals(self, intervals: List[List[int]])->int:ifnot intervals:return0
intervals.sort()
n =len(intervals)
f =[1]for i inrange(1, n):
f.append(max((f[j]for j inrange(i)if intervals[j][1]<= intervals[i][0]), default=0)+1)return n -max(f)
funceraseOverlapIntervals(intervals [][]int)int{
n :=len(intervals)if n ==0{return0}
sort.Slice(intervals,func(i, j int)bool{return intervals[i][0]< intervals[j][0]})
dp :=make([]int, n)for i :=range dp {
dp[i]=1}for i :=1; i < n; i++{for j :=0; j < i; j++{if intervals[j][1]<= intervals[i][0]{
dp[i]=max(dp[i], dp[j]+1)}}}return n -max(dp...)}funcmax(a ...int)int{
res := a[0]for_, v :=range a[1:]{if v > res {
res = v
}}return res
}
第四百三十六题:
classSolution{public:
vector<int>findRightInterval(vector<vector<int>>& q){int n = q.size();for(int i =0; i < n; i ++) q[i].push_back(i);sort(q.begin(), q.end());
vector<int>res(n,-1);for(auto& x: q){int l =0, r = n -1;while(l < r){int mid = l + r >>1;if(q[mid][0]>= x[1]) r = mid;else l = mid +1;}if(q[r][0]>= x[1]) res[x[2]]= q[r][2];}return res;}};
classSolution{publicint[]findRightInterval(int[][] intervals){int[] res =newint[intervals.length];
Map<int[], Integer> hash =newHashMap<>();for(int i =0; i < intervals.length; i++){
hash.put(intervals[i], i);}
Arrays.sort(intervals,(a, b)-> a[0]- b[0]);for(int i =0; i < intervals.length; i++){int min = Integer.MAX_VALUE;int minindex =-1;for(int j = i +1; j < intervals.length; j++){if(intervals[j][0]>= intervals[i][1]&& intervals[j][0]< min){
min = intervals[j][0];
minindex = hash.get(intervals[j]);}}
res[hash.get(intervals[i])]= minindex;}return res;}}
classSolution:deffindRightInterval(self, intervals: List[List[int]])-> List[int]:
n =len(intervals)# 排序前给每一项添加索引for i inrange(n):
intervals[i].append(i)# 按 start 排序
intervals.sort(key=operator.itemgetter(0))
res =[-1]*n
for i inrange(n):
l, r = i+1, n-1# 不存在的情况if intervals[r][0]<intervals[i][1]:continuewhile l<r:
m =(l+r)//2if intervals[m][0]>=intervals[i][1]: r = m
else: l = m+1
res[intervals[i][2]]= intervals[r][2]return res
classSolution{public List<Integer>findAnagrams(String s, String p){int n = s.length(), m = p.length();
List<Integer> res =newArrayList<>();if(n < m)return res;int[] pCnt =newint[26];int[] sCnt =newint[26];for(int i =0; i < m; i++){
pCnt[p.charAt(i)-'a']++;}int left =0;for(int right =0; right < n; right++){int curRight = s.charAt(right)-'a';
sCnt[curRight]++;while(sCnt[curRight]> pCnt[curRight]){int curLeft = s.charAt(left)-'a';
sCnt[curLeft]--;
left++;}if(right - left +1== m){
res.add(left);}}return res;}}
classSolution:deffindAnagrams(self, s:str, p:str)-> List[int]:
n, m, res =len(s),len(p),[]if n < m:return res
p_cnt =[0]*26
s_cnt =[0]*26for i inrange(m):
p_cnt[ord(p[i])-ord('a')]+=1
left =0for right inrange(n):
cur_right =ord(s[right])-ord('a')
s_cnt[cur_right]+=1while s_cnt[cur_right]> p_cnt[cur_right]:
cur_left =ord(s[left])-ord('a')
s_cnt[cur_left]-=1
left +=1if right - left +1== m:
res.append(left)return res
funcFindAnagrams(s string, p string)[]int{
res :=make([]int,0)
left :=0//左指针
right :=0//右指针
lenth :=len(s)//字符串长度
aim :=make(map[byte]int)
now :=make(map[byte]int)
nownum :=0//当前满足的种类for i,_:=range p {
aim[p[i]]+=1//记录所有的字符个数}
aimnum :=len(aim)//字符种类for right <= lenth-1{for nownum != aimnum && right <= lenth-1{//移动右指针if aim[s[right]]!=0&& aim[s[right]]> now[s[right]]{//判断字符是否符合要求,且该种类字符数量尚未满足
now[s[right]]+=1if now[s[right]]== aim[s[right]]{
nownum +=1}}elseif aim[s[right]]!=0&& aim[s[right]]<= now[s[right]]{//如果该种类字符数量满足了,则只加个数,不加种类数
now[s[right]]+=1}
right +=1}for nownum == aimnum &&(right-left)<= lenth {//移动左指针if right-left ==len(p){//当长度相等,且种类数相等时,一定满足条件
res =append(res, left)}if aim[s[left]]!=0{
now[s[left]]-=1if now[s[left]]< aim[s[left]]{
nownum -=1}}
left +=1}}return res
}