代码题(3)— 最小的k个数、数组中的第K个最大元素、前K个高频元素

时间:2023-03-08 23:42:57
代码题(3)— 最小的k个数、数组中的第K个最大元素、前K个高频元素

  1、题目:输入n个整数,找出其中最小的K个数。
  例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4。

  快排思路(掌握):

class Solution {
public:
vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
vector<int> result;
if(input.empty() || k<= || input.size()<k)
return result;
int low = ;
int high = input.size() - ;
int index = partition(input, low, high);
while(index != k-)
{
if(index <= k- )
{
low = index + ;
index = partition(input, low, high);
}
else
{
high = index - ;
index = partition(input, low, high);
}
}
for(int i =; i<k; ++i)
{
result.push_back(input[i]);
}
return result;
}
int partition(vector<int> &input, int low, int high)
{
int temp = input[low];
while(low < high)
{
while(low<high && temp < input[high])
high--;
input[low] = input[high];
while(low<high && temp >=input[low])
low++;
input[high] = input[low];
}
input[low] = temp;
return low;
}
};

  使用容器的方法:

class Solution {
public:
vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
vector<int> result;
if(input.empty() || k< || input.size()<k)
return result;
priority_queue<int> pq;
for(int i=;i<input.size();i++)
{
if(pq.size()<k)
{
pq.push(input[i]);
}
else
{
int maxVal=pq.top();
if(input[i]<maxVal)
{
pq.pop();
pq.push(input[i]);
}
}
}
while(!pq.empty())
{
result.push_back(pq.top());
pq.pop();
}
return result; }
};

2、215、数组中的第K个最大元素

题目:在未排序的数组中找到第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。

示例 1:

输入: [3,2,1,5,6,4] 和 k = 2
输出: 5

示例 2:

输入: [3,2,3,1,2,4,5,5,6] 和 k = 4
输出: 4
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
if(nums.empty() || nums.size()<k || k<=)
return -;
vector<int> copyNums = nums;
int low = ;
int high = nums.size()-;
int index = partition(nums, low, high);
while(index != k-)
{ if(low<high && index < k-)
{
low = index+;
index = partition(nums,low, high);
}
else if(low<high && index > k-)
{
high = index-;
index = partition(nums, low,high); }
else
break;
}
for(int i=;i<nums.size();++i)
{
if(copyNums[i] == nums[index])
return copyNums[i];
}
return -; }
int partition(vector<int> &input, int low, int high)
{
int temp = input[low];
while(low < high)
{
while(low<high && temp > input[high])
high--;
input[low] = input[high];
while(low<high && temp <=input[low])
low++;
input[high] = input[low];
}
input[low] = temp;
return low;
}
};

 3、347. 前K个高频元素

给定一个非空的整数数组,返回其中出现频率前 高的元素。

示例 1:

输入: nums = [1,1,1,2,2,3], k = 2
输出: [1,2]

示例 2:

输入: nums = [1], k = 1
输出: [1]

说明:

  • 你可以假设给定的 总是合理的,且 1 ≤ k ≤ 数组中不相同的元素的个数。
  • 你的算法的时间复杂度必须优于 O(n log n) , 是数组的大小。
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int> m;
priority_queue<pair<int,int>> q;
vector<int> res; for(int a:nums)
m[a]++;
for(auto it:m)
q.push({it.second, it.first});
for(int i=;i<k;++i)
{
res.push_back(q.top().second);
q.pop();
}
return res;
}
};