414. Third Maximum Number

来源:互联网 发布:欧立讯写频软件 编辑:程序博客网 时间:2024/05/18 13:28

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: 1Explanation: The third maximum is 1.

Example 2:

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

Example 3:

Input: [2, 2, 3, 1]Output: 1Explanation: 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来分别保存第一大、第二大和第三大的数,然后遍历数组,如果遍历到的数字大于当前first,那么三个变量各自错位赋值,如果当前数字大于second且小于first,那么就更新second和third,如果当前数字大于third且小于second,那就只更新third。

注意:1初始化要用长整型long的最小值Long.MIN_VALUE,因为当数组中存在整型MIN_VALUE时,无法判断返回第一大还是第三大。当然,可以设置标志位flag=False,如果存在赋值动作就flag=true。

2 最后要换回int型,在前面加(int)third,而不是int(third)。

public class Solution {    public int thirdMax(int[] nums) {        long first=Long.MIN_VALUE;        long second=Long.MIN_VALUE;        long third=Long.MIN_VALUE;        for(int num:nums){            if(num>first){                third=second;                second=first;                first=num;            }else if(num<first&&num>second){                third=second;                second=num;            }else if(num<second&&num>third){                third=num;            }        }        if(third==Long.MIN_VALUE) return (int)first;        return (int)third;     }}


原创粉丝点击