classSolution: defisHappy(self, n: int) -> bool: defchange(x: int) -> int: ret = 0 while x: x, digit = divmod(x, 10) ret += digit * digit return ret st = set() while n notin st: if n == 1: returnTrue st.add(n) n = change(n) returnFalse
// 4 ms, 7.2 MB /** * // This is the MountainArray's API interface. * // You should not implement it, or speculate about its implementation * class MountainArray { * public: * int get(int index); * int length(); * }; */
classSolution { public: template<typename Func> intbinary_search(MountainArray& mountainArr, int target, int l, int r, Func func){ target = func(target); while (l <= r) { int mid = (l + r) / 2; int cur = func(mountainArr.get(mid)); if (cur == target) return mid; if (cur < target) l = mid + 1; else r = mid - 1; } return-1; }
intfindInMountainArray(int target, MountainArray &mountainArr){ int l = 0, r = mountainArr.length() - 1; while (l < r) { int mid = (l + r) / 2; if (mountainArr.get(mid) < mountainArr.get(mid + 1)) { l = mid + 1; } else { r = mid; } } int peak = l; int index = binary_search(mountainArr, target, 0, peak, [](int x) { return x; }); if (index != -1) return index; index = binary_search(mountainArr, target, peak + 1, mountainArr.length() - 1, [](int x) { return -x; }); return index; } };
Apr.28 数组中数字出现的次数
分组异或。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// 40 ms, 16.1 MB classSolution { public: vector<int> singleNumbers(vector<int>& nums){ int xor_all = 0; for (int val : nums) xor_all ^= val; // xor_all 中 1 的位表示两个只出现过一次的数中这一位不同 int bit = xor_all & -xor_all; // 以 lowbit(xor_all) 区分两个组别 int a = 0, b = 0; // 对这两个组别分别做异或 for (int val : nums) { if (val & bit) a ^= val; else b ^= val; } return {a, b}; } };
// 0 ms, 6.4 MB classSolution { public: intsearch(vector<int>& nums, int target){ if (nums.empty()) { return-1; }
int p = 0, q = 1; while (q) { if (p + q >= nums.size() || nums[p + q] < nums[p]) { q >>= 1; } else { p += q; q <<= 1; } }
// nums[p] is the biggest value in nums. int l, r; if (target >= nums[0]) { // the target's index is in [0, p]. l = -1; r = p + 1; } else { // the target's index is in [p+1, nums.size()-1]. l = p; r = nums.size(); } while (l + 1 < r) { int mid = (l + r) >> 1; if (nums[mid] <= target) { l = mid; } else { r = mid; } } return l >= 0 && nums[l] == target ? l : -1; } };
// 380 ms, 62.9 MB classSolution { public: intnumberOfSubarrays(vector<int>& nums, int k){ int n = nums.size(); int l = 0, r = -1, cnt = 0; int ans = 0; while (r + 1 < n) { // 在 cnt < k 时继续拓展右端点 while (r + 1 < n && cnt < k) cnt += nums[++r] & 1; if (r >= n) break; int k_cnt_right_begin = r;
// 在维持 cnt == k 的前提下,再尽量移动右端点 while (r + 1 < n && !(nums[r + 1] & 1)) ++r;
// 则满足 cnt == k 的区间的左端点为 l // 右端点为 [k_cnt_right_begin, r] 之一 while (l <= r && cnt == k) { ans += r - k_cnt_right_begin + 1; cnt -= nums[l++] & 1; } } return ans; } };
# 80 ms, 14.4 MB classSolution: defnumIslands(self, grid: List[List[str]]) -> int: ifnot grid: return0 n, m = len(grid), len(grid[0]) # 为了保护 grid 数组,不直接使用 grid 数组进行标记 vis = [[False] * m for _ in range(n)] q = collections.deque() ans = 0 for i in range(n): for j in range(m): if grid[i][j] == '1'and vis[i][j] == False: q.append((i, j)) vis[i][j] = True ans += 1 while q: x, y = q.popleft() for a, b in (x-1, y), (x+1, y), (x, y-1), (x, y+1): if0 <= a < n and0 <= b < m and grid[a][b] == '1'andnot vis[a][b]: q.append((a, b)) vis[a][b] = True return ans
Apr.19 统计重复个数
Apr.18 盛最多水的容器
1 2 3 4 5 6 7 8 9 10 11 12
# 68 ms, 15.2 MB classSolution: defmaxArea(self, height: List[int]) -> int: l, r = 0, len(height) - 1 ans = 0 while l < r: ans = max(ans, (r - l) * min(height[l], height[r])) if height[l] < height[r]: l += 1 else: r -= 1 return ans
Apr.17 跳跃游戏
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// 8 ms, 7.8 MB classSolution { public: boolcanJump(vector<int>& nums){ constint n = nums.size(); int rightmost = 0; for (int i = 0; i < n && i <= rightmost; i++) { rightmost = max(rightmost, i + nums[i]); } return rightmost >= n - 1; } };
Apr.16 合并区间
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# 52 ms, 14.6 MB classSolution: defmerge(self, intervals: List[List[int]]) -> List[List[int]]: intervals.sort() ans = [] left, right = -1, -1 for interval in intervals: if interval[0] > right: if left != -1: ans.append([left, right]) left, right = interval else: right = max(right, interval[1]) # why max: cases like [[1, 4], [2, 3]] if left != -1: ans.append([left, right]) return ans
constint n = matrix.size(); constint m = matrix[0].size(); constint go[4][2] = {{0, -1}, {0, 1}, {-1, 0}, {1, 0}};
queue<PII> q; vector<vector<int>> dist(n, vector<int>(m, INF)); for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) if (matrix[i][j] == 0) { q.emplace(i, j); dist[i][j] = 0; } while (!q.empty()) { PII now = q.front(); q.pop(); for (int i = 0; i < 4; i++) { int x = now.first + go[i][0]; int y = now.second + go[i][1]; if (x >= 0 && y >= 0 && x < n && y < m && dist[x][y] == INF) { dist[x][y] = dist[now.first][now.second] + 1; q.emplace(x, y); } } } return dist; } };
// 76 ms, 20.5 MB classTwitter { public: /** Initialize your data structure here. */ Twitter(): time(0) {} /** Compose a new tweet. */ voidpostTweet(int userId, int tweetId){ mp[userId].addTweet(time, tweetId); } /** Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent. */ vector<int> getNewsFeed(int userId){ priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> heap; for (int followee : mp[userId].followees) { for (const pair<int, int>& timeId : mp[followee].tweets) { heap.push(timeId); if (heap.size() > 10) heap.pop(); } } for (const pair<int, int>& timeId : mp[userId].tweets) { heap.push(timeId); if (heap.size() > 10) heap.pop(); } vector<int> res; res.reserve(heap.size()); while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); } reverse(res.begin(), res.end()); return res; } /** Follower follows a followee. If the operation is invalid, it should be a no-op. */ voidfollow(int followerId, int followeeId){ if (followerId == followeeId) return; mp[followerId].followees.insert(followeeId); } /** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */ voidunfollow(int followerId, int followeeId){ mp[followerId].followees.erase(followeeId); }
private: structNode { unordered_set<int> followees; list<pair<int, int>> tweets; // 1st-time, 2nd-id voidaddTweet(int& time, int id){ if (tweets.size() == 10) tweets.pop_back(); tweets.emplace_front(++time, id); } }; int time; unordered_map<int, Node> mp; };
/** * Your Twitter object will be instantiated and called as such: * Twitter* obj = new Twitter(); * obj->postTweet(userId,tweetId); * vector<int> param_2 = obj->getNewsFeed(userId); * obj->follow(followerId,followeeId); * obj->unfollow(followerId,followeeId); */
classSolution: def superEggDrop(self, K: int, N: int) -> int: def f(x): ans = 0 r = 1 for i in range(1, K+1): r *= x-i+1 r //= i ans += r if ans >= N: break return ans
lo, hi = 1, N while lo < hi: mi = (lo + hi) // 2 if f(mi) < N: lo = mi + 1 else: hi = mi return lo
voiddropLFU(){ if (key_iter_map.empty()) return; auto iter = --frequency_nodeList_map[minFreq].end(); key_iter_map.erase(iter->key); frequency_nodeList_map[minFreq].pop_back(); if (frequency_nodeList_map[minFreq].empty()) { frequency_nodeList_map.erase(minFreq); ++minFreq; } } }; /** * Your LFUCache object will be instantiated and called as such: * LFUCache* obj = new LFUCache(capacity); * int param_1 = obj->get(key); * obj->put(key,value); */