首页 > 编程语言 > 详细

【LeetCode】数组-9(414)-O(n)内找到第三大的数

时间:2017-08-21 23:40:55      阅读:341      评论:0      收藏:0      [点我收藏+]

思路:

  从前向后遍历,用三个变量first second third 保存前三个大的数,初值设为long类型的无穷小(因为开始提交到案遇到负的临界值的情况),如果新来的数大于first则 second first依次后移并且把这歌新值赋值给first

【正确代码】

 1 class Solution {
 2     public int thirdMax(int[] nums) {
 3         long first = nums[0], second = Long.MIN_VALUE, third = Long.MIN_VALUE;
 4         if (nums.length == 1) {
 5             return (int)nums[0];
 6         }
 7         if (nums.length == 2) {
 8             return nums[0] > nums[1] ? (int)nums[0] : (int)nums[1];
 9         }
10         int count = 0;
11         for (int i = 1; i < nums.length; i++) {
12             if (nums[i] > first) {
13                 third = second;
14                 second = first;
15                 first = nums[i];
16             }else if (nums[i] > second && nums[i] < first) {
17                 third = second;
18                 second = nums[i];
19             }else if (nums[i] < second && nums[i] > third) {
20                 third = nums[i];
21             }else {
22                 continue;
23             }
24             count++;
25         }
26         if (count < 2) {
27             return (int)first;
28         }
29         return (int)third;
30     }
31 }

有时间想想用treeset的容器做一下。

【LeetCode】数组-9(414)-O(n)内找到第三大的数

原文:http://www.cnblogs.com/StoneLuo/p/7407220.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!