当前位置: 首页 > news >正文

leet code - Third Maximum Number

题目描述
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).


返回数组中第三大的数字,可能会包含重复。


思路:
直接遍历过程中存最大值求出结果。


public class Solution {
    public int ThirdMax(int[] nums) 
    {
		if(nums == null || nums.Length == 0){
			throw new ArgumentException();
		}
		if(nums.Length == 1){
			return nums[0];
		}
		if(nums.Length == 2){
			return Math.Max(nums[0],nums[1]);
		}
		
		int max = nums[0];
		for(var i = 1;i < nums.Length; i++){
			if(nums[i] > max){
				max = nums[i];
			}
		}
	
		int? second = null;
		for(var i = 0;i < nums.Length; i++){
			if(nums[i] < max && (second == null || nums[i] > second)){
				second = nums[i];
			}
		}
		
		if(!second.HasValue){
			return max;
		}
		
		int? third = null;
		for(var i = 0;i < nums.Length; i++){
			if(nums[i] < second && (third == null || nums[i] > third)){
				third = nums[i];
			}
		}
		
		if(third.HasValue){
			return third.Value;
		}
		else{
			return max;
		}
		
	
	}
	




}


相关文章:

  • 关于中国软件发展的讨论沙龙
  • SQL server replication的三种方式
  • leetcode -- Count Numbers with Unique Digits
  • javascript小数四舍五入
  • 业务场景和业务用例场景的区别(作者:Arthur网友)
  • Android -- 打开时隐藏软键盘
  • 邀请大象一书的读者和广大网友写关于分析设计、建模方面的自愿者文章
  • Android -- 读取NFC卡号
  • Windows 7安装以及VS2008和Office2007冲突的问题
  • C# Windows form application 播放小视频
  • 系列文章—内容模型系统开发总结一
  • LeetCode -- Coin chane
  • LeetCode -- Ransom Note
  • LeetCode -- Divide Two Integers
  • 背板带宽
  • CAP 一致性协议及应用解析
  • IDEA常用插件整理
  • Java超时控制的实现
  • js对象的深浅拷贝
  • Logstash 参考指南(目录)
  • PhantomJS 安装
  • Redis 中的布隆过滤器
  • Vue ES6 Jade Scss Webpack Gulp
  • vue自定义指令实现v-tap插件
  • 得到一个数组中任意X个元素的所有组合 即C(n,m)
  • 动态魔术使用DBMS_SQL
  • 番外篇1:在Windows环境下安装JDK
  • 基于Android乐音识别(2)
  • 紧急通知:《观止-微软》请在经管柜购买!
  • 坑!为什么View.startAnimation不起作用?
  • 模仿 Go Sort 排序接口实现的自定义排序
  • 前端面试题总结
  • 算法-插入排序
  • 自制字幕遮挡器
  • 进程与线程(三)——进程/线程间通信
  • 正则表达式-基础知识Review
  • ​ ​Redis(五)主从复制:主从模式介绍、配置、拓扑(一主一从结构、一主多从结构、树形主从结构)、原理(复制过程、​​​​​​​数据同步psync)、总结
  • ​软考-高级-系统架构设计师教程(清华第2版)【第1章-绪论-思维导图】​
  • ​业务双活的数据切换思路设计(下)
  • #if #elif #endif
  • $jQuery 重写Alert样式方法
  • $refs 、$nextTic、动态组件、name的使用
  • (1)Nginx简介和安装教程
  • (MIT博士)林达华老师-概率模型与计算机视觉”
  • (定时器/计数器)中断系统(详解与使用)
  • (二)斐波那契Fabonacci函数
  • (附源码)ssm捐赠救助系统 毕业设计 060945
  • (三) diretfbrc详解
  • (十一)JAVA springboot ssm b2b2c多用户商城系统源码:服务网关Zuul高级篇
  • (原創) 如何解决make kernel时『clock skew detected』的warning? (OS) (Linux)
  • (转)关于pipe()的详细解析
  • .NET Core WebAPI中使用Log4net 日志级别分类并记录到数据库
  • .NET6 开发一个检查某些状态持续多长时间的类
  • .netcore 获取appsettings
  • .skip() 和 .only() 的使用