[LeetCode]414. Third Maximum Number

来源:互联网 发布:ewb仿真软件简介 编辑:程序博客网 时间:2024/06/16 17:10

题目描述:Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n).

分析:
Example 1:
Input: [3, 2, 1]
Output: 1
Explanation: The third maximum is 1.

Example 2:
Input: [1, 2]
Output: 2
Explanation: The third maximum does not exist, so the maximum (2) is returned instead.

Example 3:
Input: [2, 2, 3, 1]
Output: 1
Explanation: Note that the third maximum here means the third maximum distinct number.
Both numbers with value 2 are both considered as second maximum.

分析:返回第三大的数,如果不存在则返回最大的数。

解题思路:遍历,将first、second、third存储并返回第三大的数,如果不存在则返回最大的数。

public int thirdMax(int[] nums) {        Integer first = null;        Integer second = null;        Integer third = null;        for(int i=0;i<nums.length;i++){            if(first==null||nums[i]>first){                third = second;                second = first;                first = nums[i];            }else if(second==null||nums[i]>second){                if(nums[i]==first)continue;                third = second;                second = nums[i];            }else if(third==null||nums[i]>third){                if(nums[i]==second)continue;                third = nums[i];            }        }        return third==null?first:third;     }
原创粉丝点击