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.
读题
这个题目的意思就是选出一个数组中第三大的数,需要注意的是相同的数字只算做一次
思路
非常暴力的做法就是先去重使用set,然后遍历筛选过后的数组找到第三大的数,如果这个筛选的数组元素的个数小于等于2就直接返回最大的数
题解
public class Solution414 {
public static int thirdMax(int[] nums) {
Set set = new HashSet<Integer>();
for (int i = 0; i < nums.length; i++) {
set.add(nums[i]);
}
List<Integer> list = new ArrayList<Integer>(set);
if (list.size() == 1)
return list.get(0);
if (list.size() == 2)
return list.get(0) > list.get(1) ? list.get(0) : list.get(1);
int a = list.get(0);
int b = list.get(0);
int c = list.get(0);
for (int i = 1; i < list.size(); i++) {
if (list.get(i) > b) {
if (list.get(i) > a) {
c = b;
b = a;
a = list.get(i);
}
if (list.get(i) < a) {
c = b;
b = list.get(i);
}
}
if (list.get(i) < b) {
if (list.get(i) > c)
c = list.get(i);
}
}
return c;
}
public static void main(String[] args) {
int[] arr = new int[] {1,2,3};
int result = Solution414.thirdMax(arr);
System.out.println(result);
// System.out.println(Integer.MIN_VALUE);
}
}