领扣(LeetCode)第三大的数 个人题解

给定一个非空数组,返回此数组中第三大的数。如果不存在,则返回数组中最大的数。要求算法时间复杂度必须是O(n)。

示例 1:

输入: [3, 2, 1]

输出: 1

解释: 第三大的数是 1.

示例 2:

输入: [1, 2]

输出: 2

解释: 第三大的数不存在, 所以返回最大的数 2 .

示例 3:

输入: [2, 2, 3, 1]

输出: 1

解释: 注意,要求返回第三大的数,是指第三大且唯一出现的数。
存在两个值为2的数,它们都排第二。

第一次遇到这个题目,想到的办法就是定义三个数,第一大,第二大,第三大,然后依次判断。这个办法行之有效。但是最开始没写出来正确答案,因为没有考虑到去重的问题。
由于考虑到去重,所以我又想到用集合来解决,把数组放到集合里面去,放的时候就去掉重复的元素,最后得到一个没有重复的集合。然后再对集合进行排序,判断是否有第三大的数,最后得到正确答案。
但是这样做,算法的复杂度就达到了O(n2)的级别。虽然能得到正确答案,也能通过领扣的测试,成功AC,但是速度之低令人发指,只打败了提交的1%的人。
代码如下:
 1 class Solution {
 2     public int thirdMax(int[] nums) {
 3         Vector v=new Vector();
 4         for (int i : nums) {
 5             if(!v.contains(i))
 6                 v.add(i);
 7         }
 8         v.sort(null);
 9         if(v.size()>=3)
10             return (int) v.get(v.size()-3);
11         else
12             return (int) v.get(v.size()-1);
13     }
14 }
然后重新思考最开始的做法,他的算法复杂度是O(n),然后参考了相关的代码,发现可以使用Integer这个JAVA内封装好的类,设置值为null,来表示未被放置过的数。同时,加了忽略掉重复的元素逻辑,成功AC。
代码如下:
 1 class Solution {
 2     public int thirdMax(int[] nums) {
 3         Integer fmax = null, smax = null, tmax = null;
 4         for (int i : nums) {
 5             if ((fmax != null && fmax == i) || (smax != null && smax == i) || (tmax != null && tmax == i))
 6                 continue;
 7             if (fmax == null || i > fmax) {
 8                 tmax = smax;
 9                 smax = fmax;
10                 fmax = i;
11             } else if (smax == null || i > smax) {
12                 tmax = smax;
13                 smax = i;
14             } else if (tmax == null || i > tmax) {
15                 tmax = i;
16             }
17         }
18         return tmax == null ? fmax : tmax;
19     }
20 }
 

猜你喜欢

转载自www.cnblogs.com/axiangcoding/p/9898243.html