Skip to content

Instantly share code, notes, and snippets.

@ozkansari
Last active April 13, 2020 06:30
Show Gist options
  • Save ozkansari/aadec9c065e8f08f002761a1507415b3 to your computer and use it in GitHub Desktop.
Save ozkansari/aadec9c065e8f08f002761a1507415b3 to your computer and use it in GitHub Desktop.
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. https://leetcode.com/explore/challenge/card/30-day-leetcoding-challenge/528/week-1/3289/
import java.util.*;
import java.util.stream.*;
class CountingConsecutiveElements {
public int countElements(int[] arr) {
Map<Integer, Integer> numberCounts = new HashMap<>();
for(int num : arr) {
Integer wrappedNum = Integer.valueOf(num);
int currentCount = numberCounts.getOrDefault(wrappedNum,0);
numberCounts.put(wrappedNum,currentCount+1);
}
int result = 0;
for(Map.Entry<Integer, Integer> currentEntry: numberCounts.entrySet()) {
int currentNum = currentEntry.getKey().intValue();
int currentCount = currentEntry.getValue().intValue();
int relatedNumCount = numberCounts.getOrDefault(currentNum+1, 0);
// Even if there is only one x+1, count all x's. E.g. [1,2,2]
result += relatedNumCount == 0 ? 0 : currentCount;
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment