LeetCode414——Third Maximum Number

来源:互联网 发布:单片机如何控制舵机 编辑:程序博客网 时间:2024/05/15 06:28

题意
已知一个数组,求出数组中第三大的数,如果数组数目小于3,则返回最大值。
代码
方法一:先对数组进行排序,然后从后至前进行遍历

import java.util.Arrays;public class Solution {    public int thirdMax(int[] nums) {        int res=Integer.MIN_VALUE;        int count=0;        Arrays.sort(nums);        for(int i=nums.length-1;i>=0;i--) {            if(res!=nums[i]) {                  //去除重复出现的数                res=nums[i];                count++;                        //对目前最大数进行数目累加            }            if(count==3)break;                  //等于3时结束遍历            }        //当数组按照大小去重排序后数目小于三个时输出最大值        if(count<3)                                         res=nums[nums.length-1];        return res;    }}

Runtime: 5 ms

方法二:使用三个Integer类型的数来存储数组中最大的三个数

public class Solution2 {    public static int thirdMax(int[] nums) {        Integer max1=null;        Integer max2=null;        Integer max3=null;        for(Integer n:nums) {            if(n.equals(max1)||n.equals(max2)||n.equals(max3))continue;            if(max1==null||n>max1) {                                    //此处不可以写成if(n>max1||max1==null)因为max的初始值为null,无法与n比较大小,所以会抛出空指针异常                max3=max2;                max2=max1;                max1=n;            }            else if(max2==null||n>max2) {                max3=max2;                max2=n;            }            else if(max3==null||n>max3){                max3=n;            }        }        return max3==null?max1:max3;    }}

Runtime: 9 ms

原创粉丝点击