Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n).
Example 1:
Input: [3, 2, 1] Output: 1 Explanation: The third maximum is 1.
Example 2:
Input: [1, 2] Output: 2 Explanation: The third maximum does not exist, so the maximum (2) is returned instead.
Example 3:
Input: [2, 2, 3, 1] Output: 1 Explanation: Note that the third maximum here means the third maximum distinct number. Both numbers with value 2 are both considered as second maximum.给一个非空数组,找第三大的数,第一想到的就是先排序,再输出第三大的数。基于这个思想,见下面代码:
public class Solution {
public int thirdMax(int[] nums) {
if (nums.length == 0) {
return 0;
}
Arrays.sort(nums);
int count = 0;
int i = nums.length - 1;
while (i > 0) {
if (nums[i] != nums[i - 1]) {
count ++;
}
if (count >= 2)
break;
i --;
}
if (count < 2) {
return nums[nums.length - 1];
} else {
return nums[i - 1];
}
}
}
但是Array.sort() 的时间复杂度是O(nlogn),不符合题目要求。所以想到下面的解法,用一个数组保存top3的数,按升序保存,每次改变 top3[0]的值,重新排列数组,这样可以保证top3大的数永远在后三位,且为升序排列。代码如下:
public class Solution {
public int thirdMax(int[] nums) {
if (nums.length == 0) {
return 0;
}
int[] top3 = {Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE};
HashSet<Integer> hs = new HashSet<Integer>();
int i = 0;
int p = 0;
for (; i < nums.length; i ++) {
if (!hs.contains(nums[i])) {
hs.add(nums[i]);
top3[0] = nums[i];
//Array.sort() O(nlogn)
Arrays.sort(top3);
p ++;
}
}
if (p < 3) {
return top3[3];
} else {
return top3[1];
}
}
}
上面代码的时间复杂度是O(n),符合要求。