Solution that uses Comparable


  • 0
    D

    Although in-efficient [O(n^2)]

    Spoiler

    public class Solution {
    public int findPairs(int[] nums, int k) {
    if(k < 0) {
    return 0;
    }

        Set<Pair> result = new HashSet<Pair>();
    
        for(int i = 0 ; i < nums.length - 1 ; i++) {
            for(int j = (i+1); j < nums.length ; j++) {
                if(Math.abs(nums[i] - nums[j]) == k) {
                    result.add(new Pair(nums[i], nums[j]));
                }
            }
        }
    
        Set<Pair> finalResult = new TreeSet<>();
        
        for(Pair pair: result) {
            finalResult.add(pair);
        }
        
        return finalResult.size();
    }
    

    }

    class Pair implements Comparable<Pair> {
    int x, y;

    public Pair(int x, int y) {
        this.x = (x < y) ? x : y;
        this.y = (x < y) ? y : x;
    }
    
    public int compareTo(Pair newPair) {
        if(this.x == newPair.x && this.y == newPair.y) {
            return 0;
        } else if(this.x < newPair.x || (this.x == newPair.x && this.y < newPair.y)) {
            return -1;
        } else {
            return 1;
        }
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.