Day 7 of 30-Day LeetCode Challenge

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.

class Solution {
public:
int countElements(vector<int>& arr) { //O(nlogn)
sort(arr.begin(), arr.end());
int result = 0;
for(int i=0;i<arr.size();){
int j = i+1;
while(j<arr.size()&&arr[i]==arr[j]){
++j;
}
if(j<arr.size()&&arr[i]+1==arr[j]) {
//cout<<i<<”, “<<j<<endl;
result += j-i;
}

i = j;
}
return result;
}
};

--

--

We never really grow up, we only learn how to act in public

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store