题目:Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n).
Example 1:
Input: [3, 2, 1]
Output: 1
Explanation: The third maximum is 1.
Example 2:
Input: [1, 2]
Output: 2
Explanation: The third maximum does not exist, so the maximum (2) is returned instead.
Example 3: Input: [2, 2, 3, 1] Output: 1 Explanation: Note that the third maximum here means the third maximum distinct number. Both numbers with value 2 are both considered as second maximum.
给出的框架如下
following is the given framework
class Solution {
public:
int thirdMax(vector<int>& nums) {
}
};尝试1:将vector中的元素按照从大到小的顺序进行排序;
判断不同元素的个数,如果大于等于3,输出第三大的数字,否则输出第一大的数字(就是第一个元素)
代码如下:
class Solution {
public:
bool reverse_sort(int a,int b){
return a>b;
}
int thirdMax(vector<int>& nums) {
sort(nums.begin(),nums.end(),reverse_sort);
if(nums.size()<3) return nums[0];
int cnt=0;
for(int i=1;i<nums.size();i++){
if(nums[i-1]!=nums[i]) cnt++;
if(cnt==2) return nums[i];
}
return nums[0];
}
};但是提示sort函数错误,可能是因为不给使用库函数而且库函数快排的时间复杂度为n*logn ,不符合题意
尝试2:
设置一个三元素数组,初始值为最小整数-(1<<31),遍历一次向量,如果向量元素值大于当前数组元素,将向量元素插入数组,并将数组值从当前开始整体后移一位,最后一位舍弃。依次遍历向量。结束后判断数组最后一位元素是否为-(1<<31),如果不是证明存在第三大的元素,输出;如果是,证明不存在第三大元素,输出第一位元素(必为最大值)。
但是存在一个问题:向量中的元素也有可能是最小整数,如此,判定第三大元素存在与否的条件便不成立了(这也是为什么提交了好多次);
于是:设置一个标志变量和一个移位变量,当向量中存在最小整数的时候,flag置1,否则为0;移位变量初始为0,当出现最小整数的时候置为最小整数在数组中的索引,当数组元素调整一次,移位变量增加一。最后判断:不存在第三大元素条件:(数组最后一位是最小整数)并且(最小整数在向量中没有出现或者移位变量值<2(没有移到最后一位)) ;否则的话便存在第三大元素,输出数组第三位。
代码如下:
class Solution {
public:
int thirdMax(vector<int>& nums) {
int a[3];
int flag = 0, numofmove = 0;
a[0] = a[1] = a[2] = -(1 << 31);
for (int j, i = 0; i < nums.size(); i++){
for ( j = 0; j< 3 && nums[i] < a[j]; j++);
if (j != 3 && nums[i] == -(1 << 31)) {
flag = 1; numofmove = j;
}
if (j != 3 && nums[i] != a[j]){
numofmove++;
int tempt=a[j];
a[j] = nums[i];
while (j != 2)
{
j++;
int box = a[j];
a[j] = tempt;
tempt = box;
}
}
}
if (a[2] == -(1 << 31)&&(flag==0||flag==1&&numofmove<2)) return a[0];
return a[2];
}
};算法复杂度分析:遍历向量一次:每次遍历遍历数组一次,复杂度为O(3n);
在此,有幸被大师看到本篇blog的话,希望在我之上的46.33%的大师能留下您的代码
本文探讨了如何在整数数组中找到第三大的数,提出了一种线性时间复杂度的解决方案,避免使用排序函数,并通过实例解释了算法实现细节。
816

被折叠的 条评论
为什么被折叠?



