LeetCode Array Easy 414. Third Maximum Number
2024-09-05 08:29:47
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;
}
最新文章
- iOS 关于PCH文件(全局文件)的介绍
- jquery实现input输入框实时输入触发事件代码(点击历史记录也会触发)
- Js中 md5 sha1 base64 加密
- JavaScript-String基础知识
- IBM x3850 x5 服务器 安装 Windows Server 2008
- ubuntu 跟xshell的问题
- Androd开发之广告栏设计
- 通过两根RS232连接两台电脑
- IO端口和IO内存
- android ListView的怪异现象
- ActiveReports 9实战教程(2): 准备数据源(设计时、运行时)
- js 拖拽实现
- 如何得到AdoConnection.execute(sqlstr)执行的返回结果
- angular中的$q服务
- 【bzoj2819】Nim
- Vue(二)基础
- LeetCode - 769. Max Chunks To Make Sorted
- CIFAR10数据可视化
- 【精】【入门篇】js正则表达式
- PHP 日期时间类 Carbon 的常见用法
热门文章
- Linux修改密码指令
- 消费者与生产者---LinkedList方式模拟
- 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
- ubuntu 彻底删除软件
- C#基础提升系列——C#委托
- 回顾Servlet及SpringMVC
- mybatis源码分析之04Mapper接口的动态代理
- 生成100个 ";20180520"; 这样的时间字符串 写入txt文件
- Python常用内置函数整理(lambda,reduce,zip,filter,map)
- PHP curl_close函数