classSolution { public: intsumOfSquares(vector<int>& nums){ int n = nums.size(); int res = 0; for (int i = 0; i < nums.size(); i++) { if (n % (i + 1) == 0) { res += nums[i] * nums[i]; } } return res; } };
classSolution { public: intmaximumBeauty(vector<int>& nums, int k){ sort(nums.begin(), nums.end()); int maxVal = *max_element(nums.begin(), nums.end()); int res = 0; for (int i = 0; i <= maxVal; i++) { int l = i - k; int r = i + k; auto it1 = upper_bound(nums.begin(), nums.end(), r); auto it2 = lower_bound(nums.begin(), nums.end(), l); int d = it1 - it2; res = max(res, d); } return res;
} };
classSolution { public: intmaximumBeauty(vector<int>& nums, int k){ sort(nums.begin(), nums.end()); int ans = 0; for (int i = 0, j = 0; i < nums.size(); i++) { while (i < nums.size() && nums[i] - nums[j] > 2 * k) { j++; } ans = max(ans, i - j + 1); } return ans; } };
2780. 合法分割的最小下标
如果元素 x 在长度为 m 的整数数组 arr 中满足 freq(x) * 2 > m ,那么我们称 x 是 支配元素 。其中 freq(x) 是 x 在数组 arr 中出现的次数。注意,根据这个定义,数组 arr最多 只会有 一个 支配元素。
给你一个下标从 0 开始长度为 n 的整数数组 nums ,数据保证它含有一个支配元素。
你需要在下标 i 处将 nums 分割成两个数组 nums[0, ..., i] 和 nums[i + 1, ..., n - 1] ,如果一个分割满足以下条件,我们称它是 合法 的:
classSolution { public: intminimumIndex(vector<int>& nums){ int n = nums.size(); int val = 0; int total = 0; unordered_map<int, int> cnt; for (auto v : nums) cnt[v]++; for (auto [x, freq] : cnt) { if (freq * 2 > n) { val = x; total = freq; } } int curr = 0; for (int i = 0; i < n - 1; i++) { if (nums[i] == val) { curr++; } if (curr * 2 > (i + 1) && (total - curr) * 2 > (n - i - 1)) { return i; } } return-1; } };
intsearch(struct Trie *trie, string &word){ structTrie *node = trie; for (auto c : word) { if (node->next[c - 'a'] == nullptr) { return-1; } node = node->next[c - 'a']; if (node->isWord) { return node->len; } } return-1; }
classSolution { public: intlongestValidSubstring(string word, vector<string>& forbidden){ structTrie *trie = newTrie(); int maxlen = 0; for (auto w : forbidden) { insertTrie(trie, w); maxlen = max(maxlen, int(w.size())); } int n = word.size(); int res = 0; for (int l = n - 1, r = n - 1; l >= 0; l--) { string curr = word.substr(l, min(r - l + 1, maxlen)); int len = search(trie, curr); if (len < 0) { res = max(res, r - l + 1); } else { r = l + len - 2; } } return res; } };