HR-Pairs

https://www.hackerrank.com/challenges/pairs

Given integers, count the number of pairs of integers whose difference is K.

解体思路: Set

边界条件: 数组有值。 1 直接解题, 先把数组排序,然后从前往后,找 v+k的值,如果数组值已近大于 v+k, 停止查询。从头继续下一个值查找。

    Arrays.sort(arr);
    int total = 0;
    for(int i = 0; i < n-1; i++){
        //System.out.println(arr[i]);
        int j = i+1;
        while(j<n && (arr[i] + k) > arr[j]){
            j++;
        }
        if(j<n && (arr[i] + k) == arr[j] ){
            total++;
        }
    }

2 使用 HashSet, 每值放入hashset, 同时比较 v+k 还是 v-k 在不在 set里,如果再就总数加

    int total = 0;
    HashSet<Integer> set= new HashSet<Integer>();
    for(int v : a){           
        if(set.contains(v-k)){
            total++;
        }
        if(set.contains(v+k)){
            total++;
        }
         set.add(v);
    }
    return total;

Last updated

Was this helpful?