414. Third Maximum Number
Given a non-empty array of integers, return the third maximuhttps://leetcode.com/problems/third-maximum-number/#/descriptionm 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.
题目链接:https://leetcode.com/problems/third-maximum-number/#/description
解题思路:三次遍历,第一次找出最大值,第二次找出第二大的值,第三次找出第三大的值。三个值要初始化为最小值,也就是Integer.MIN_VALUE,但给定的数组会有这个最小值,因此不能根据是第三大的值否等于初始值来判断是否找到第三大的值,加一个布尔标记就好。
代码如下:
public class Solution {
public int thirdMax(int[] nums) {
int max = Integer.MIN_VALUE;
int m2 = Integer.MIN_VALUE;
int m3 = Integer.MIN_VALUE;
boolean flog = false;
for(int i=0;i<nums.length;i++){
if(nums[i] > max){
max = nums[i];
}
}
for(int i=0;i<nums.length;i++){
if(nums[i]<max && nums[i] > m2){
m2 = nums[i];
}
}
for(int i=0;i<nums.length;i++){
if(nums[i] < m2 && nums[i] >= m3){
m3 = nums[i];
flog = true;
}
}
if(flog){
return m3;
}else{
return max;
}
}
}