Skip to content

Instantly share code, notes, and snippets.

@mustafa-qamaruddin
Created November 12, 2022 15:07
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 mustafa-qamaruddin/56e5b5e3db814e416db53c61041217d0 to your computer and use it in GitHub Desktop.
Save mustafa-qamaruddin/56e5b5e3db814e416db53c61041217d0 to your computer and use it in GitHub Desktop.
Pair Class Comparable for HashSet
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