[1,2,-2147483648] 这个测试用例真的绝了
红黑树
维护3个数的大小
java
class Solution {
public int thirdMax(int[] nums) {
if (nums == null || nums.length == 0) throw new RuntimeException("error");
TreeSet<Integer> set = new TreeSet<>();
for (Integer elem : nums) {
set.add(elem);
if (set.size() > 3) set.remove(set.first());
}
return set.size() < 3 ? set.last() : set.first(); // set.last() 里面最大的元素
}
}
最快1
class Solution {
public int thirdMax(int[] nums) {
double max = Double.NEGATIVE_INFINITY;
double sen = Double.NEGATIVE_INFINITY;
double t = Double.NEGATIVE_INFINITY;
int count = 0;
for (int num : nums) {
if (num <= t || num == max || num == sen) {
continue;
} else if (num > max) {
t = sen;
sen = max;
max = num;
count++;
} else if (num > sen) {
t = sen;
sen = num;
count++;
} else {
t = num;
count++;
}
}
return count < 3 ? (int)max : (int)t;
}
}
想法最简单的
java
class Solution {
public int thirdMax(int[] nums) {
Arrays.sort(nums);
List<Integer>res=new ArrayList<Integer>();
for(int i=0;i<nums.length;i++) {
if(!res.contains(nums[i])) {
res.add(nums[i]);
}
}
if(res.size()<3)return res.get(res.size()-1);
return res.get(res.size()-3);
}
}
class Solution {
public int thirdMax(int[] nums) {
int m1=Integer.MIN_VALUE;
int m2=Integer.MIN_VALUE;
int m3=Integer.MIN_VALUE;
List<Integer>res=new ArrayList<Integer>();
for(int i=0;i<nums.length;i++) {
if(!res.contains(nums[i])) {
if(nums[i]>=m1) {
m3=m2;
m2=m1;
m1=nums[i];
}
else
if(nums[i]>=m2) {
m3=m2;
m2=nums[i];
}
else
if(nums[i]>=m3) {
m3=nums[i];
}
res.add(nums[i]);
}
}
if(res.size()<3)return m1;
else {
return m3;
}
}
}