One minute
Leetcode 1426
This solution is straightforward, and the idea of this solution is we add all the values of arr into a map called m. All we do is check whether m contains arr[i] + 1. If it does, we can add one to the resulting counter.
So the code:
- First, makes a map called
mand a variable calledres. - Then we loop through
arrand add all the values intom. - Then we loop through
arragain, but this time check whethermcontainsarr[i] + 1, and if it does, is it greater than0. If so, we can add one tores. - Now, all we have to do is return
res.
The Code:
func countElements(arr []int) int {
m := make(map[int]int)
res := 0
for _, i := range arr {
m[i]++
}
for _, i := range arr {
if m[i + 1] > 0 {
res++
}
}
return res
}
Read other posts