414:第三大的数

This commit is contained in:
huangge1199@hotmail.com 2021-07-07 23:45:06 +08:00
parent 5ada4db229
commit 4f53c6b2d0
2 changed files with 115 additions and 0 deletions

View File

@ -0,0 +1,75 @@
//给你一个非空数组返回此数组中 第三大的数 如果不存在则返回数组中最大的数
//
//
//
// 示例 1
//
//
//输入[3, 2, 1]
//输出1
//解释第三大的数是 1
//
// 示例 2
//
//
//输入[1, 2]
//输出2
//解释第三大的数不存在, 所以返回最大的数 2
//
//
// 示例 3
//
//
//输入[2, 2, 3, 1]
//输出1
//解释注意要求返回第三大的数是指在所有不同数字中排第三大的数
//此例中存在两个值为 2 的数它们都排第二在所有不同数字中排第三大的数为 1
//
//
//
// 提示
//
//
// 1 <= nums.length <= 104
// -231 <= nums[i] <= 231 - 1
//
//
//
//
// 进阶你能设计一个时间复杂度 O(n) 的解决方案吗
// Related Topics 数组 排序
// 👍 230 👎 0
package leetcode.editor.cn;
import java.util.Arrays;
import java.util.TreeSet;
//414:第三大的数
class ThirdMaximumNumber {
public static void main(String[] args) {
//测试代码
Solution solution = new ThirdMaximumNumber().new Solution();
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int thirdMax(int[] nums) {
TreeSet<Integer> set = new TreeSet<>();
for (int i : nums) {
set.add(i);
if (set.size() > 3) {
set.pollFirst();
}
}
if (set.size() < 3) {
return set.pollLast();
} else {
return set.pollFirst();
}
}
}
//leetcode submit region end(Prohibit modification and deletion)
}

View File

@ -0,0 +1,40 @@
<p>给你一个非空数组,返回此数组中 <strong>第三大的数</strong> 。如果不存在,则返回数组中最大的数。</p>
<p> </p>
<p><strong>示例 1</strong></p>
<pre>
<strong>输入:</strong>[3, 2, 1]
<strong>输出:</strong>1
<strong>解释:</strong>第三大的数是 1 。</pre>
<p><strong>示例 2</strong></p>
<pre>
<strong>输入:</strong>[1, 2]
<strong>输出:</strong>2
<strong>解释:</strong>第三大的数不存在, 所以返回最大的数 2 。
</pre>
<p><strong>示例 3</strong></p>
<pre>
<strong>输入:</strong>[2, 2, 3, 1]
<strong>输出:</strong>1
<strong>解释:</strong>注意,要求返回第三大的数,是指在所有不同数字中排第三大的数。
此例中存在两个值为 2 的数,它们都排第二。在所有不同数字中排第三大的数为 1 。</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>4</sup></code></li>
<li><code>-2<sup>31</sup> <= nums[i] <= 2<sup>31</sup> - 1</code></li>
</ul>
<p> </p>
<p><strong>进阶:</strong>你能设计一个时间复杂度 <code>O(n)</code> 的解决方案吗?</p>
<div><div>Related Topics</div><div><li>数组</li><li>排序</li></div></div>\n<div><li>👍 230</li><li>👎 0</li></div>