LeetCode#414. Third Maximum Number

来源:互联网 发布:淘宝店推广方案 编辑:程序博客网 时间:2024/06/06 10:38
  • 题目:给定一个数值,找出第三大的数(相同值的算一个),时间复杂度为o(n)
  • 难度:Easy
  • 思路:由于时间复杂度的限制,显然不能用先排序再取第三个元素,这样就容易想到用空间复杂度来换时间复杂度,所以可以定义三个变量,在遍历数值的过程中,不断更新这三个变量的值
  • 代码:
public class Solution {    public int thirdMax(int[] nums) {        if(nums.length == 1){            return nums[0];        }else if(nums.length == 2){            return Math.max(nums[0], nums[1]);        }        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){                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;    }}
原创粉丝点击