题目:
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).
注意:
1.他说是非空的,数组有可能是[1,2]这种情况。
2.时间复杂度是O(n)就不能sort,只能遍历。
3.第一遍写的时候没有看题,他说的是没有第三最大的就返回最大的,所以最后else return返回的是first不是second。
4.我第一遍写的时候是把 first 设置成nums[0],second 和 third 都设置成0,然后在循环里int i = 1 去遍历,后来发现不对,因为如果是[1,2]的情况,相当于最后是[2,1,0]。第三大返回的就是0了。
5.我开始的时候想不明白第二个判断条件,为什么不能等于first,后来终于明白了,会出现这样的结果。
Code:
class Solution {
public int thirdMax(int[] nums) {
int first = nums[0];
int second = nums[0];
int third = nums[0];
for(int i=0;i<nums.length;i++){
if(nums[i]>first){
third = second;
second = first;
first = nums[i];
}else if (nums[i]!=first && (nums[i] > second || second == first)){
third = second;
second = nums[i];
}else if((nums[i]!=first && nums[i] != second) && (nums[i] > third || third == second || third == first)){
third = nums[i];
}
}
if(first>second && second>third) return third;
else return first;
}
}