# Don't know why my code doesn't work[Solved!]

• ``````public class Solution {
public int thirdMax(int[] nums) {
int max, mid, min;
max = mid = min = Integer.MIN_VALUE;
for(int i=0; i<nums.length; i++){
if(nums[i]>max){
min = mid;
mid = max;
max = nums[i];
}else if(nums[i]>mid&&nums[i]!=max){
min = mid;
mid = nums[i];
}else if(nums[i]>min&&nums[i]!=mid){
min = nums[i];
}
}
return min == Integer.MIN_VALUE? max:min;
}
}
``````

It returns right answer when input is [3,2,1],
but it returns 5, when input is [1,2,2,5,3,5].

• @NewtonTree
Found the question in the second "else-if" statement. The element can be bigger than min but equals to max. I forgot to consider that condition.
After adjusting the statement, the code couldn't pass some tricky tests, such as [2, 1, -2147483648]. Because I set the Integer.MIN_VALUE as the null.
So I changed max, mid, min and the elements in the array into Integer class. So that I can use "null" instead of real integer.
And the Integer can't be compared when it is null. So the max mid min could be assigned at first when it is null.
Moreover, the output of [2,2,3,1] would be 2 instead of 1 if there's no statement at the beginning to tell the code to skip the same element. Because when the second 2 is smaller than max, it makes mid becomes 2 because mid is null at first.

So here's my final code, which passed the test and the runtime was 9 ms.

``````public class Solution {
public int thirdMax(int[] nums) {
Integer max, mid, min;
max = mid = min = null;
for(Integer n:nums){
if(n.equals(max)||n.equals(mid)||n.equals(min)) continue;
if(max==null||n>max){
min = mid;
mid = max;
max = n;
}else if(mid==null||n>mid){
min = mid;
mid = n;
}else if(min==null||n>min){
min = n;
}
}
return min = min==null? max:min;
}
}
``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.