文章目录
- 考查知识点
- 面试题39:数组中出现次数超过一半的数字
- 面试题40:最小的k个数
考查知识点
题目 | 知识点 |
---|
39 | 考察数组的排序 |
40 | 考察经典排序中的快速排序、及其应用 |
面试题39:数组中出现次数超过一半的数字
- 题目描述:
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
示例 1:
输入: [1, 2, 3, 2, 2, 2, 5, 4, 2]
输出: 2
限制:
1 <= 数组长度 <= 50000 - 分析:
先对数组元素进行排序;
元素个数超过一半的这个元素所在位置一定有一个是处在数组中间位置的;
输出排序后数组中间位置元素即可。 - 代码:
class Solution {
public:int majorityElement(vector<int>& nums) {int n = nums.size();if(n<1 || n>50000)return -1;sort(nums.begin(), nums.end());return nums[n/2];}
};
面试题40:最小的k个数
- 题目描述:
输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4。 - 分析:
(1)牛客AC思路:
先对特殊情况进行处理,比如输入向量为空,输入的k值小于等于0,输入的k值大于原向量的长度,则返回空;
然后直接用自带的sort函数对原向量进行从小到大排序,返回排序后的前k个数即可;
(2)剑指通过思路:
也是先排序然后再输出,但是使用的方法是快排,这种方法在本地可以通过但在牛客或leecode上超时。 - 代码牛客AC:
class Solution {
public:vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {vector<int> res;if(input.empty() || k<=0 || k>input.size())return res;sort(input.begin(), input.end());for(int i=0;i<k;i++){res.push_back(input[i]);}return res;}
};
#include<iostream>
#include<vector>
using namespace std;
int Partition(int arr[], int low, int high)
{int pivot = arr[low];while(low<high){while(low<high && arr[high]>=pivot){--high;}arr[low] = arr[high];while(low<high && arr[low]<=pivot){++low;}arr[high]=arr[low];}arr[low] = pivot;return low;
}
void GetLeastNum(int* input, int n,int* output, int k)
{if(input==nullptr || k<=0 || k>n ||n<=0)return;int pivot = Partition(input, 0, n-1);while(pivot != k-1){if(pivot>k-1){pivot = Partition(input, 0, pivot-1);}else{pivot = Partition(input, pivot+1, n-1);}}for(int i=0;i<k;i++){output[i] = input[i];}
}
int main()
{int input[] = {6,5,3,4,7,9};int k=3;int *output = (int*)malloc(sizeof(int)*k);GetLeastNum(input, 6, output,k);for(int i=0;i<k;i++){cout<<output[i];}free(output);return 0;
}
- 代码剑指的C++做法调试通过:
注意这里int Partition(vector<int> &arr, int low, int high)
的&符号,这样才能在原数组上进行排序并返回地址!!
#include<iostream>
#include<vector>
using namespace std;int Partition(vector<int> &arr, int low, int high)
{int pivot = arr[low];while(low<high){while(low<high && arr[high]>=pivot){--high;}arr[low] = arr[high];while(low<high && arr[low]<=pivot){++low;}arr[high]=arr[low];}arr[low] = pivot;return low;
}vector<int> GetLeastNumbers_Solution(vector<int> input, int k)
{int n = input.size();vector<int> r(k);int pivot = Partition(input, 0, n-1);while(pivot != k-1){if(pivot>k-1){pivot = Partition(input, 0, pivot-1);}else{pivot = Partition(input, pivot+1, n-1);}}for(int i=0;i<k;i++){r[i] = input[i];}return r;
}int main()
{int in[] = {6,5,3,4,7,9};vector<int> input(in,in+6);int k=3;vector<int> output(k);output = GetLeastNumbers_Solution(input, k);for(int i=0;i<k;i++){cout<<output[i];}return 0;
}