LeetCode#414. Third Maximum Number
来源:互联网 发布:淘宝店推广方案 编辑:程序博客网 时间:2024/06/06 10:38
- 题目:给定一个数值,找出第三大的数(相同值的算一个),时间复杂度为o(n)
- 难度:Easy
- 思路:由于时间复杂度的限制,显然不能用先排序再取第三个元素,这样就容易想到用空间复杂度来换时间复杂度,所以可以定义三个变量,在遍历数值的过程中,不断更新这三个变量的值
- 代码:
public class Solution { public int thirdMax(int[] nums) { if(nums.length == 1){ return nums[0]; }else if(nums.length == 2){ return Math.max(nums[0], nums[1]); } Integer max1 = null;//第一大 Integer max2 = null;//第二大 Integer max3 = null;//第三大 for(Integer n : nums){ if(n.equals(max1) || n.equals(max2) || n.equals(max3)){ continue; } if(max1 == null || n > max1){ max3 = max2; max2 = max1; max1 = n; }else if(max2 == null || n > max2){ max3 = max2; max2 = n; }else if(max3 == null || n > max3){ max3 = n; } } return max3 == null ? max1 : max3; }}
阅读全文
0 0
- leetcode 414. Third Maximum Number
- LeetCode:414. Third Maximum Number
- LeetCode-414. Third Maximum Number
- LeetCode 414. Third Maximum Number
- [Leetcode]414. Third Maximum Number
- LeetCode 414. Third Maximum Number
- <leetcode>414. Third Maximum Number
- Leetcode 414. Third Maximum Number
- 【LeetCode】 414. Third Maximum Number
- [leetcode]414. Third Maximum Number
- Leetcode-414. Third Maximum Number
- [leetcode]414. Third Maximum Number
- LeetCode 414. Third Maximum Number
- [LeetCode]414. Third Maximum Number
- Leetcode-414. Third Maximum Number
- 【LeetCode】414. Third Maximum Number
- LeetCode 414. Third Maximum Number
- 【Leetcode】414. Third Maximum Number
- 算法作业HW19 130. Surrounded Regions
- Java一维数组实验编程
- 矩阵交换II HDU
- html select操作
- python正则表达式
- LeetCode#414. Third Maximum Number
- TI 一主三从主机端分析【发现服务流程】
- 大牛们的ACM 算法 阶段性练习
- 观察-Watchers
- struts2拦截器
- struts2.0配置文件、常量配置详解
- 阿里云CentOS安装升级Python、pip
- diff命令详解
- idea如何连接数据库