【精】LintCode领扣算法问题答案:1250. 第三大的数
发布日期:2021-06-30 17:10:32 浏览次数:2 分类:技术文章

本文共 1340 字,大约阅读时间需要 4 分钟。

1250. 第三大的数

描述

给定一个非空数组,返回此数组中第三大的数。如果不存在,则返回数组中最大的数。要求算法时间复杂度必须是O(n)。

样例 1:

输入: 	num = [3, 2, 1]输出: 	1解释: 	第三大的数是 1.

样例 2:

输入: 	num = [1, 2]输出: 	2解释: 	第三大的数不存在, 所以返回最大的数 2 .

样例 3:

输入: 	num = [2, 2, 3, 1]输出: 	1解释: 	注意,要求返回第三大的数,是指第三大且唯一出现的数。	存在两个值为2的数,它们都排第二。


文章目录


题解

public class Solution {
/** * @param nums: the array * @return: the third maximum number in this array */ public int thirdMax(int[] nums) {
// Write your code here. long max = Long.MIN_VALUE; long second = Long.MIN_VALUE; long third = Long.MIN_VALUE; for (int i = 0; i < nums.length; i++) {
int num = nums[i]; if (num == max || num == second || num == third) {
continue; } if (num > max) {
third = second; second = max; max = num; } else if (num > second) {
third = second; second = num; } else if (num > third) {
third = num; } } if (third == Long.MIN_VALUE) {
return (int) max; } return (int )third; }}

最后说两句

非常感谢你阅读本文章,如果你觉得本文对你有所帮助,请留下你的足迹,点个赞,留个言,多谢~

作者水平有限,如果文章内容有不准确的地方,请指正。

希望小伙伴们都能每天进步一点点。

声明

本文由博客原创,转载请注明来源,谢谢~

转载地址:https://le-yi.blog.csdn.net/article/details/108907445 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:领扣LintCode算法问题答案-1253. 将数字转换为16进制
下一篇:领扣LintCode算法问题答案-1243. 字符串中的单词数

发表评论

最新留言

网站不错 人气很旺了 加油
[***.192.178.218]2024年04月07日 23时21分01秒