视频弹幕网站建设,如何把wordpress头部去掉,贵州网站设计公司,无网站营销Every day a Leetcode
题目来源#xff1a;3020. 子集中元素的最大数量
解法1#xff1a;哈希 枚举
用一个哈希表统计数组 nums 中的元素及其出现次数。
暴力枚举数组中的数#xff0c;作为 x#xff0c;然后不断看 x2,x4,⋯ 在数组中的个数。直到个数不足 2 个为止3020. 子集中元素的最大数量
解法1哈希 枚举
用一个哈希表统计数组 nums 中的元素及其出现次数。
暴力枚举数组中的数作为 x然后不断看 x2,x4,⋯ 在数组中的个数。直到个数不足 2 个为止退出循环。
注意模式的正中间的数字只取一个。如果最后 x 有一个那么个数加一否则个数减一。
注意特判 x1 的情况。
代码
/** lc appleetcode.cn id100206 langcpp** [100206] 子集中元素的最大数量*/// lc codestart
class Solution
{
public:int maximumLength(vectorint nums){// 特判if (nums.empty())return 0;unordered_maplong long, int cnt;for (int num : nums)cnt[num];// 特判 x1 的情况int ans cnt[1] - (cnt[1] % 2 0);cnt.erase(1);for (auto [num, _] : cnt){int res 0;long long x;for (x num; cnt.contains(x) cnt[x] 1; x * x)res 2;if (cnt.contains(x))res;elseres--;ans max(ans, res);}return ans;}
};
// lc codeend结果 复杂度分析
时间复杂度O(nloglogU)其中 n 为数组 nums 的长度Umax(nums)。
空间复杂度O(n)。