Skip to content

Instantly share code, notes, and snippets.

@shixiaoyu
Created July 18, 2020 05:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shixiaoyu/64be9d75606ea1e8e9ba8c5070523e34 to your computer and use it in GitHub Desktop.
Save shixiaoyu/64be9d75606ea1e8e9ba8c5070523e34 to your computer and use it in GitHub Desktop.
public int numIdenticalPairsWithSort(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
Arrays.sort(nums);
int goodPairsCount = 0;
int start = 0;
int end = 0;
while (end < nums.length) {
if (nums[end] == nums[start]) {
end++;
continue;
}
// if you have n occurrences of a number, the good pair is n*(n-1)/2, Cn^2
int delta = end - start;
if (delta > 1) {
goodPairsCount += delta * (delta - 1) / 2;
}
start = end;
}
// handle the case 1, 2, 3, 3, 3
if (start != nums.length - 1) {
goodPairsCount += (end - start) * (end - start - 1) / 2;
}
return goodPairsCount;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment