Description

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: [, , ]

Output: 

Explanation: The third maximum is . 

Example 2:

Input: [, ]

Output: 

Explanation: The third maximum does not exist, so the maximum () is returned instead. 

Example 3:

Input: [, , , ]

Output: 
Explanation: Note that the third maximum here means the third maximum distinct number.
Both numbers with value 2 are both considered as second maximum.

问题描述,给定要给非空数组,找出第三大的数,如果找不到则返回最大值。

思路:用三个数分别存最大 第二 第三大的值。但是由于数组中会出现int的最小边界值。所以干脆用long类型来存储前三个值。

public int ThirdMax(int[] nums) {
long max = long.MinValue;
long sec = long.MinValue;
long third = long.MinValue; for(int i = ; i < nums.Length; i++){
int temp = nums[i];
if(temp > max){
third = sec;
sec = max;
max=temp;
}
else if(temp < max && temp >sec){
third = sec;
sec=temp;
}
else if(temp < sec && temp >=third){
third = temp;
} }
return third > long.MinValue ? (int)third : (int)max;
}

最新文章

  1. iOS 关于PCH文件(全局文件)的介绍
  2. jquery实现input输入框实时输入触发事件代码(点击历史记录也会触发)
  3. Js中 md5 sha1 base64 加密
  4. JavaScript-String基础知识
  5. IBM x3850 x5 服务器 安装 Windows Server 2008
  6. ubuntu 跟xshell的问题
  7. Androd开发之广告栏设计
  8. 通过两根RS232连接两台电脑
  9. IO端口和IO内存
  10. android ListView的怪异现象
  11. ActiveReports 9实战教程(2): 准备数据源(设计时、运行时)
  12. js 拖拽实现
  13. 如何得到AdoConnection.execute(sqlstr)执行的返回结果
  14. angular中的$q服务
  15. 【bzoj2819】Nim
  16. Vue(二)基础
  17. LeetCode - 769. Max Chunks To Make Sorted
  18. CIFAR10数据可视化
  19. 【精】【入门篇】js正则表达式
  20. PHP 日期时间类 Carbon 的常见用法

热门文章

  1. Linux修改密码指令
  2. 消费者与生产者---LinkedList方式模拟
  3. spring boot启动异常:java.sql.SQLException: The server time zone value &#39;&#214;&#208;&#185;&#250;&#177;&#234;&#215;&#188;&#202;&#177;&#188;&#228;&#39; is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver
  4. ubuntu 彻底删除软件
  5. C#基础提升系列——C#委托
  6. 回顾Servlet及SpringMVC
  7. mybatis源码分析之04Mapper接口的动态代理
  8. 生成100个 &quot;20180520&quot; 这样的时间字符串 写入txt文件
  9. Python常用内置函数整理(lambda,reduce,zip,filter,map)
  10. PHP curl_close函数