- 第三大的数
给你一个非空数组,返回此数组中 第三大的数 。如果不存在,则返回数组中最大的数。
提示:
1 <= nums.length <= 104
-231 <= nums[i] <= 231 - 1
示例 1:
输入:[3, 2, 1]
输出:1
解释:第三大的数是 1 。
示例 2:
输入:[1, 2]
输出:2
解释:第三大的数不存在, 所以返回最大的数 2 。
示例 3:
输入:[2, 2, 3, 1]
输出:1
解释:注意,要求返回第三大的数,是指在所有不同数字中排第三大的数。
此例中存在两个值为 2 的数,它们都排第二。在所有不同数字中排第三大的数为 1 。
解析过程:
该方法满足O(n);
class Solution {
public int thirdMax(int[] nums) {
if(nums.length==0||nums==null)
return 0;
if(nums.length==1) //如果数组长度为1
return nums[0];
if(nums.length==2) //如果数组长度为2
return Math.max(nums[0],nums[1]);
int flag=0;
int first=Integer.MIN_VALUE;
int second=Integer.MIN_VALUE;
int third=Integer.MIN_VALUE;
boolean f=true;
for(int i=0;i<nums.length;i++){
if(nums[i]>first){
flag++;
third=second; //将第二大的数传给第三大
second=first; //将第一大的数传给第二大,后面依次类推
first=nums[i];
}else if(nums[i]>second&&nums[i]<first){
flag++;
third=second;
second=nums[i];
}else if(nums[i]>third && nums[i]<second){
flag++;
third=nums[i];
}else if(nums[i]==Integer.MIN_VALUE&&f){
flag++;
f=false;
}
}
return flag>=3 ? third:first;
}
}
结果:
执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户
内存消耗:38.1 MB, 在所有 Java 提交中击败了79.73%的用户
通过测试用例:31 / 31
该方法不满足O(n);
class Solution {
public int thirdMax(int[] nums) {
if(nums==null||nums.length==0)
return 0;
Arrays.sort(nums); //从小到大排序,时间复杂度已经超过O(n)
ArrayList<Integer> list=new ArrayList<>();
for(int i=0;i<nums.length;i++){
if(!list.contains(nums[i])){//contains()速度会很慢
list.add(nums[i]);
}
}
if(nums.length<3){
return list.get(list.size()-1);
}
else {
return list.get(list.size()-3);
}
}
}