Lets say I have a variable num
.
Before I can evaluate an if
statement, I need to check if this variable has been set in the first place. Typically I would use either -1
, 0
or math.MaxInt32/math.MinInt32
but for this task I need to check if my program has set its value.
I tried nums := nil
and in my if
statement I had something like if nums == nil || ...
.
But when creating the nums
variable I was surprised to get the error cannot convert nil to type int
. How I can achieve what I want to do?
To make it clear: This is a leetcode question and don't have control of the inputs, they put all sorts of numbers inside include math.MaxInt32, math.MinInt32
Full code:
func thirdMax(nums []int) int {
dict := make(map[int]int, 0)
varmaxOne := math.MinInt32
maxTwo := math.MinInt32
maxThree := math.MinInt32
for _, value := range nums {
if value >= maxOne && dict[value] < 1 {
maxThree = maxTwo
maxTwo = maxOne
maxOne = value
}else if value >= maxTwo && dict[value] < 1{
maxThree = maxTwo
maxTwo = value
} else if value >= maxThree && dict[value] < 1 {
maxThree = value
}
dict[value] += 1
}
if maxThree == math.MinInt32 {
return maxTwo
}
return maxThree
}
func max(a int, b int) int {
if a > b {
return a
}
return b
}
Test
func TestThirdMax(t *testing.T) {
//array := []int{2, 3, -1, -9, 11, 4, 3, 0, -100}
//array := []int{2, 2, 3, 1}
array := []int{1,2,-2147483648}
//array := []int{3,2,1}
result := thirdMax(array)
if result != 2 {
t.Errorf("Expected 2, but it was %d instead.", array)
}
}
The code above use math.MinInt32
, but fails with the input given. The idea was to have nil
instead and put a check in the if
statement, but fails as stated above.