Leetcode - Counting Elements
Given an integer array arr, count element x such that x + 1 is also in arr.
If there're duplicates in arr, count them seperately.
Example 1:
Input: arr = [1,2,3] Output: 2 Explanation: 1 and 2 are counted cause 2 and 3 are in arr.
func countElements(arr []int) int {
count := make([]int, 1001)
for _, a := range arr {
count[a]++
}
result := 0
for i := 0; i < len(count)-1; i++ {
if count[i] > 0 && count[i+1] > 0 {
result += count[i]
}
}
return result
}
评论 (0)