414. Third Maximum Number

xiaoxiao2021-02-28  143

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来分别保存第一大、第二大和第三大的数,然后遍历数组,如果遍历到的数字大于当前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; } }

转载请注明原文地址: https://www.6miu.com/read-29103.html

最新回复(0)