Skip to main content

Counting Elements

LeetCode Link

Problem Description​

Visit LeetCode for the full problem description.


Solutions​

Solution 1: C# (Best: 84 ms)​

MetricValue
Runtime84 ms
Memory23.9 MB
Date2020-04-07
Solution
public class Solution {
public int CountElements(int[] arr) {
Array.Sort(arr);
int count=0;
for (int i = 0; i < arr.Length-1; )
{
int j =i;
while(i+1<arr.Length && arr[i+1]== arr[i])
{
i++;
}

if(i==j && (arr[i]+1) == arr[i+1])
count++;
else if(i+1<arr.Length && arr[i+1]==(arr[j]+1))
{
count += (i-j+1);
}
i++;
}
return count;
}
}

Complexity Analysis​

ApproachTimeSpace
SolutionTo be analyzedTo be analyzed