Re: [闲聊] 每日LeetCode

楼主: Pash97143 (四叶天下第一)   2023-05-23 03:28:45
※ 引述《Rushia (みけねこ的鼻屎)》之铭言:
: https://leetcode.com/problems/top-k-frequent-elements/description/
: 347. Top K Frequent Elements
: 给你一个阵列 nums,找出出现次数最多次的前k个元素是哪些。
: Example 1:
: Input: nums = [1,1,1,2,2,3], k = 2
: Output: [1,2]
: Example 2:
: Input: nums = [1], k = 1
: Output: [1]
好久没写leetcode了,决定回来写
之前遇到学校作业太多,就会不想写leetcode,希望之后能坚持住
写个C++的,内存在90%以上,但速度是10%以下QQ
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
for (int n : nums) {
int r = isInVector(n);
if (r == -1) {
vc.push_back(make_pair(n, 1));
}
else {
vc[r].second++;
}
}
sort(vc.begin(), vc.end(), [](pair<int, int> a, pair<int, int> b) {
return a.second > b.second;
});
vector<int> result;
for (int i = 0; i < k; i++) {
result.push_back(vc[i].first);
}
return result;
}
private:
int isInVector(int n) {
int count = -1;
for (auto p : vc) {
count++;
if (n == p.first)
return count;
}
return -1;
}
vector<pair<int, int>> vc;
};
作者: pandix (面包屌)   2023-05-23 04:03:00
跑到O(n^2)去了

Links booklink

Contact Us: admin [ a t ] ucptt.com