LeetCode数组遍历414

122 阅读1分钟

🍀 第三大的数

描述:

 # 给你一个非空数组,返回此数组中 第三大的数 。如果不存在,则返回数组中最大的数。
 ​
 示例 1:
 输入:[3, 2, 1]
 输出:1
 解释:第三大的数是 1 。
 ​
 示例 2:
 输入:[1, 2]
 输出:2
 解释:第三大的数不存在, 所以返回最大的数 2 。
 ​
 示例 3:
 输入:[2, 2, 3, 1]
 输出:1
 解释:注意,要求返回第三大的数,是指在所有不同数字中排第三大的数。
 此例中存在两个值为 2 的数,它们都排第二。在所有不同数字中排第三大的数为 1 。
  
 提示:
 1 <= nums.length <= 104
 -231 <= nums[i] <= 231 - 1
 ​
 进阶:你能设计一个时间复杂度 O(n) 的解决方案吗?

思考:

题中描述很简单,返回数组中第三大的数,利用java排序得到顺序序列,然后再找出第三大的数。排序后比较一次比较两个数,不同则获得两个不同的数,所以需要两次不同即可,两次不同后返回不同数所在数组中的前一个数(因为是从后往前找第三大的)!

实现:

 class Solution {
     public int thirdMax(int[] nums) {
 ​
         int third = 0, different = 0;
 ​
         // 1.排序数组
         Arrays.sort(nums);
 ​
         for (int i=nums.length - 1; i > 0; i--){
             if (nums[i] != nums[i-1]){
                 // 2.找出不同的次数
                 different++;
                 if (different == 2){
                     return nums[i-1];
                 }
             }
         }
 ​
         // 只有一个 || 有重复的一个 || 有两个不同返回最大的
         return nums[nums.length - 1];
 ​
     }
 }

测试一下!

image.png

大佬的代码:

大佬代码这个flag弄的就很灵性,和我方法中的different差不多。

 class Solution {
     public int thirdMax(int[] nums) {
         if(nums.length==1){
             return nums[0];
         }
         if(nums.length==2){
             return Math.max(nums[0],nums[1]);
         }
         int max1=Integer.MIN_VALUE;
         int max2=Integer.MIN_VALUE;
         int max3=Integer.MIN_VALUE;
         boolean f=true;
         int flag=0;
         for(int i=0;i<nums.length;i++){
             if(nums[i]==Integer.MIN_VALUE&&f){
                 flag++;
                 f=false;
             }
             if(nums[i]>max1){
                 flag++;
                 //原先第二大传递给第三大
                 max3=max2;
                 //原先最大值传递给第二大
                 max2=max1;
                 //更新最大值
                 max1=nums[i];
             }else if (nums[i]>max2 && nums[i]<max1){
                 flag++;
                 max3=max2;
                 max2=nums[i];
             } else if( nums[i]>max3 && nums[i]<max2){
                 flag++;
                 max3=nums[i];
             }
         }
         return flag>=3?max3:max1;
     }
 }

\