Created
November 12, 2022 15:07
-
-
Save mustafa-qamaruddin/56e5b5e3db814e416db53c61041217d0 to your computer and use it in GitHub Desktop.
Pair Class Comparable for HashSet
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
class Solution { | |
private class Pair implements Comparable<Pair> { | |
private int a; | |
private int b; | |
public Pair(int a, int b) { | |
this.a = a; | |
this.b = b; | |
} | |
public int a() { return a;} | |
public int b() { return b;} | |
@Override | |
public int compareTo(Pair p2) { | |
if (this.a() == p2.a() && this.b() == p2.b()) return 0; | |
return 1; | |
} | |
} | |
public int distinctAverages(int[] nums) { | |
Set<Pair> pairs = new TreeSet<>(); | |
Set<Float> ret = new HashSet<>(); | |
Arrays.sort(nums); | |
int i = 0; int j = nums.length - 1; | |
while (i < j) { | |
Pair p = new Pair(nums[i], nums[j]); | |
if (!pairs.contains(p)) { | |
pairs.add(p); | |
float avg = (p.a() + p.b()) / 2; | |
ret.add(avg); | |
} | |
i++; | |
j--; | |
} | |
var it = pairs.iterator(); | |
while (it.hasNext()) { | |
Pair p = it.next(); | |
} | |
return ret.size(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment