题目链接:
力扣https://leetcode-cn.com/problems/third-maximum-number/
【方法一】直接去重后排序,选第三小的值出来
class Solution {
public int thirdMax(int[] nums) {
Set<Integer> set = new HashSet<Integer>();
int n = nums.length;
for (int i = 0; i < n; i ++) set.add(nums[i]);
Object[] tmp = set.toArray();
Arrays.sort(tmp);
n = tmp.length;
if(n < 3) return (int) tmp[n - 1];
return (int)tmp[n - 3];
}
}
【方法二】三个变量a,b,c分别记录前三大的数。
class Solution {
public int thirdMax(int[] nums) {
long a = (long)Integer.MIN_VALUE - 1, b = (long)Integer.MIN_VALUE - 1, c = (long)Integer.MIN_VALUE - 1;
int n = nums.length, i, flag = 0;
for(i = 0; i < n; i++){
if(nums[i] > a){
c = b; b = a; a = nums[i];
}else if(nums[i] < a && nums[i] > b){
c = b; b = nums[i];
}else if(nums[i] < b && nums[i] > c){
c = nums[i]; flag = 1;
}
}
return c == (long)Integer.MIN_VALUE - 1? (int)a: (int)c;
}
}
【方法三】使用java的TreeSet
class Solution {
public int thirdMax(int[] nums) {
TreeSet<Integer> set = new TreeSet<>();
for(Integer it: nums){
set.add(it);
if(set.size() > 3) set.remove(set.first());
}
return set.size() == 3 ? set.first(): set.last();
}
}