Leetcode 239.滑动窗口最大值
题目链接:239.滑动窗口最大值
思路:自己做法有点忘了,粘的之前做的最大值过来的。。。
自己做法:
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
int hh = 0, tt = -1;
vector<int> result;
vector<int> queue(nums.size());
for(int i = 0; i < nums.size(); i++) {
if(hh <= tt && i - k + 1 > queue[hh]) hh++;
while(hh <= tt && nums[queue[tt]] <= nums[i]) tt--;
queue[++tt] = i;
if(i >= k - 1) result.push_back(nums[queue[hh]]);
}
return result;
}
};
class Solution {
private:
class MyQueue{
public:
deque<int> que;
void pop(int value) {
if(!que.empty() && value == que.front()) que.pop_front();
}
void push(int value) {
while(!que.empty() && value > que.back()) que.pop_back();
que.push_back(value);
}
int getMax() {
return que.front();
}
};
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
MyQueue window;
vector<int> result;
for(int i = 0; i < k; i++) {
window.push(nums[i]);
}
result.push_back(window.getMax());
for(int i = k; i < nums.size(); i++) {
window.pop(nums[i - k]);
window.push(nums[i]);
result.push_back(window.getMax());
}
return result;
}
};
Leetcode 347.前K个高频元素
题目链接:347.前K个高频元素
思路:我的思路就是哈希表,然后用value去排序整个哈希表,因此要自己写一个cmp函数,然后再用sort函数去排,最后输出前k个数的key就行了。而代码随想录的做法是根据小根堆来做的,一样是用哈希表记录每个数的出现的次数,但用小根堆来排序并只排序前k个数,这样的话时间复杂度会下来。
自己做法:
class Solution {
public:
static bool cmp(pair<int, int> a, pair<int, int> b) {
return a.second > b.second;
}
vector<int> topKFrequent(vector<int>& nums, int k) {
map<int, int> m;
vector<int> result;
for(int i = 0; i < nums.size(); i++) {
m[nums[i]]++;
}
vector<pair<int, int>> vec(m.begin(), m.end());
int count = 0;
sort(vec.begin(), vec.end(), cmp);
for(auto iter = vec.begin(); iter != vec.end(); iter++) {
if(count == k) break;
result.push_back(iter->first);
count++;
}
return result;
}
};
代码随想录做法:
class Solution {
class mycomparison {
public:
bool operator()(const pair<int, int>& lhs, const pair<int, int>& rhs) {
return lhs.second > rhs.second;
}
};
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
vector<int> result(k);
priority_queue<pair<int, int>, vector<pair<int, int>>, mycomparison> pri_que;
unordered_map<int, int> map;
for(int i = 0; i < nums.size(); i++) {
map[nums[i]] ++;
}
for(auto iter = map.begin(); iter != map.end(); iter++) {
pri_que.push(*iter);
if(pri_que.size() > k) {
pri_que.pop();
}
}
for(int i = k - 1; i >= 0; i--) {
result[i] = pri_que.top().first;
pri_que.pop();
}
return result;
}
};
栈与队列总结
文章链接:总结