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.
找出数组中第三大的数,如果不存在的话那么就返回最大的数。
注意: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; }}
阅读全文
0 0
- 414. Third Maximum Number
- 414. Third Maximum Number
- 414. Third Maximum Number
- 414. Third Maximum Number
- 414. Third Maximum Number
- 414. Third Maximum Number
- 414. Third Maximum Number
- 414. Third Maximum Number
- 414. Third Maximum Number
- 414. Third Maximum Number
- 414. Third Maximum Number
- 414. Third Maximum Number
- 414. Third Maximum Number
- 414. Third Maximum Number
- 414. Third Maximum Number
- 414. Third Maximum Number*
- 414. Third Maximum Number
- 414. Third Maximum Number
- 我的python3基础笔记之 【字符串和编码】
- 小文本——Cookies
- 在phpcms模板页面中如何调用验证码以及实现验证码验证?
- 初学spring遇到的问题1
- 匈牙利命名法相关命名表
- 414. Third Maximum Number
- Smart Form中四种窗口类型的区别
- centos7.3源码编译httpd-2.4.27
- 史上最全最详细JNDI数据源配置说明
- 进程通信之共享内存2
- 文章标题
- Jquery(一)基础核心
- CodeForces
- Xshell无法连接ubuntu的问题解决