LeetCode & Q414-Third Maximum Number-Easy

Array Math

Description:

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.

刚开始不会写,想先排序再找,发现超级麻烦,就放弃了,看了Discuss,直接用数学的方法来比较大小就好,我感觉我永远都get不到题目想让我怎么解....

public class Solution {
public int thirdMax(int[] nums) {
Integer num1 = null;
Integer num2 = null;
Integer num3 = null; for (Integer num : nums) {
if (num.equals(num1) || num.equals(num2) || num.equals(num3)) continue;
if (num1 == null || num > num1) {
num3 = num2;
num2 = num1;
num1 = num;
} else if (num2 == null || num > num2) {
num3 = num2;
num2 = num;
} else if (num3 == null || num > num3) {
num3 = num;
}
} return num3 == null ? num1 : num3;
}
}
上一篇:WIN7,安装所以软件都提示error writing temporary file


下一篇:oracle 多行变一行 wmsys.wm_concat