Solution#2
public class Solution {
public int thirdMax(int[] nums) {
int max, mid, min;
max = mid = min = Integer.MIN_VALUE;
int count = 0;
for (int x : nums) {
if (x == max || x == mid) continue;
if ( x > max) {
min = mid;
mid = max;
max = x;
count++;
} else if (x > mid) {
min = mid;
mid = x;
count++;
} else if (x > min) {
min = x;
count++;
}
}
return count >= 3 ? min : max;
}
}
Solution#1
public class Solution {
public int thirdMax(int[] nums) {
int[] top = new int[3];
for (int i = 0; i < 3; i++) {
top[i] = Integer.MIN_VALUE;
}
int hasMin = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == Integer.MIN_VALUE) hasMin = 1;
if (nums[i] > top[0]) {
top[2] = top[1];
top[1] = top[0];
top[0] = nums[i];
}
if (nums[i] < top[0]) {
if (nums[i] > top[1]) {
top[2] = top[1];
top[1] = nums[i];
}
if (nums[i] < top[1]) {
if (nums[i] > top[2]) top[2] = nums[i];
}
}
}
int count = 0;
for (int x : top) {
if (x == Integer.MIN_VALUE) count++;
}
if (count - hasMin != 0) return top[0];
return top[2];
}
}
Problem#1
* 有时需要将数组默认初始化值改变
* 三个数可以不用数组