funcfindTheLongestBalancedSubstring(s string)int { res := 0 for i := 0; i < len(s);{ x, y := 0, 0 for i < len(s) && s[i] == '0' {x++; i++} for i < len(s) && s[i] == '1' {y++; i++} res = max(res, min(x, y) * 2) // 这个01连续字符串中0字符串和1字符串最小长度*2 } return res } funcmax(x, y int)int {if x > y {return x}; return y} funcmin(x, y int)int {if x < y {return x}; return y}
funcfindMatrix(nums []int) [][]int { var res [][]int mp := make(map[int]int) for _, x := range nums { mp[x]++ // 记录元素个数 } forlen(mp) != 0 { var tmp []int for k := range mp { tmp = append(tmp, k) mp[k]-- if mp[k] == 0 { delete(mp, k) // 这个元素用完直接删除 } } res = append(res, tmp) } return res }
funcmiceAndCheese(a []int, b []int, k int)int { res := 0 type s struct { z, x, y int } tmp := make([]s, len(a)) for i := 0; i < len(a); i++ { tmp[i] = s{a[i]-b[i], a[i], b[i]} } // 按照差值排序 sort.Slice(tmp, func(i, j int)bool{ return tmp[i].z > tmp[j].z }) for i := 0; i < len(tmp); i++ { if i < k { // 老鼠1选择前k个 res += tmp[i].x }else { res += tmp[i].y } } return res }
classSolution { public: vector<int> minReverseOperations(int n, int p, vector<int>& banned, int k){ vector<int> res(n, -2); res[p] = 0; for (int x : banned) res[x] = -1; // 还没被跳到的位置, 按奇偶放入set set<int> st[2]; for (int i = 0; i < n; i++) if (res[i] == -2) st[i % 2].insert(i);
queue<int> q; q.push(p); while (!q.empty()) { int cur = q.front(); q.pop(); // 计算可以跳的范围 int l, r; l = max(-(k - 1), k - 1 - cur * 2); r = min(k - 1, -(k - 1) + (n - cur - 1) * 2);
int x = (cur + (k - 1)) % 2; auto it = st[x].lower_bound(cur + l); // 找第一个大于等于的cur + l的位置 while (it != st[x].end()) { if (*it > cur + r) break; // 超过界限 res[*it] = res[cur] + 1; // 可以跳 q.push(*it); // 加入队列 it = st[x].erase(it); } } for(int i = 0; i < n; i++) if(res[i] == -2) res[i] = -1; return res; } };