Created
July 18, 2020 05:46
-
-
Save shixiaoyu/64be9d75606ea1e8e9ba8c5070523e34 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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