classSolution: defstringMatching(self, words: List[str]) -> List[str]: ans = set() n = len(words) for i inrange(n): for j inrange(i + 1, n): if words[i].find(words[j]) != -1: ans.add(words[j]) if words[j].find(words[i]) != -1: ans.add(words[i]) return [i for i in ans]
1409. Queries on a Permutation With Key
用List模拟Permutation的变化。
寻找位置时使用顺序查找。
时间复杂度: O(m + queries.length * m),
空间复杂度: O(m + queries.length).
classSolution { public: vector<int> processQueries(vector<int>& queries, int m){ list<int> P; for (int i = 1; i <= m; ++i) { P.push_back(i); } vector<int> ans(queries.size()); for (int i = 0; i < queries.size(); ++i) { auto it = P.begin(); int position = 0; while (it != P.end() && *it != queries[i]) { ++it; ++position; } ans[i] = position; P.push_front(*it); P.erase(it); } return ans; } };
classSolution { public: intcountLargestGroup(int n){ unordered_map<int, int> seen; int largestSize = 0; for (int i = 1; i <= n; ++i) { int sumOfDigit = 0; int current = i; while (current > 0) { sumOfDigit += current % 10; current /= 10; } ++seen[sumOfDigit]; largestSize = max(largestSize, seen[sumOfDigit]); } int ans = 0; for (auto it = seen.begin(); it != seen.end(); ++it) { if (it->second == largestSize) ++ans; } return ans; } };
classSolution { public: boolcanConstruct(string s, int k){ if (s.size() < k) returnfalse; vector<int> count(26, 0); for (char c : s) { ++count[c - 'a']; } int single = 0; for (int i : count) { if (i % 2 == 1) ++single; } return single <= k; } };
classSolution { public: intfindTheDistanceValue(vector<int>& arr1, vector<int>& arr2, int d){ int ans = 0; sort(arr2.begin(), arr2.end()); for (int i : arr1) { auto it1 = lower_bound(arr2.begin(), arr2.end(), i - d); auto it2 = upper_bound(arr2.begin(), arr2.end(), i + d); if (it1 == it2) ++ans; } return ans; } };
classSolution { unordered_map<int, int> memo; unordered_map<int, int> sumDivisors; intdivisors(int x){ if (x == 1) return1; else { if (memo.find(x) == memo.end()) { int ans = 2; int sum = 1 + x; for (int i = 2; i * i <= x; ++i) { if (x % i == 0) { ans += (i * i == x) ? 1 : 2; sum += (i * i == x) ? i : i + x / i; } if (ans > 4) break; } if (ans == 4) { sumDivisors[x] = sum; } return memo[x] = ans; } else { return memo[x]; } } } public: intsumFourDivisors(vector<int>& nums){ int ans = 0; for (int i : nums) { if (divisors(i) == 4) ans += sumDivisors[i]; } return ans; } };
for (int iCase = 1; iCase <= T; ++iCase) { int N, B; cin >> N >> B; for (int i = 0; i < N; ++i) { cin >> A[i]; } sort(A.begin(), A.begin() + N); int ans = 0; int index = 0; while (index < N && B >= A[index]) { B -= A[index]; ++ans; ++index; } cout << "Case #" << iCase << ": " << ans <<endl; }