Sort by

recency

|

1244 Discussions

|

  • + 0 comments

    include

    using namespace std; int test(int n, long long k, vector a) { int dem = 0; unordered_sets(a.begin(), a.end()); for(int i = 0; i < n; i++) { if(a[i] > k){ long long tam = a[i] - k; if(s.find(tam) != s.end()) { dem++; } } } return dem; } int main() { int n; long long k; cin >> n >> k; vector a(n); for(int i = 0; i < n; i++) { cin >> a[i]; } cout << test(n, k, a); return 0; }

  • + 0 comments

    C#

    public static int pairs(int k, List<int> arr)
    {
        var hashSet = new HashSet<int>(arr);
        return hashSet.Count(x => hashSet.Contains(x + k));
    }
    
    
    public static int pairs(int k, List<int> arr)
    {
        var total = 0;
        var hashSet = new HashSet<int>(arr);
    
        foreach (var n in hashSet)
        {
            if (hashSet.Contains(n + k))
            {
                total++;
            }
        }
    
        return total;
    }
    
  • + 0 comments

    Python 3:

    from collections import Counter

    counter = Counter(arr) num_pairs = 0

    for i in arr: if i - k in counter: num_pairs += 1 # Note: integers in arr are distinct

    return num_pairs

  • + 0 comments

    Simple C++ sol using set | O(n)

    `c++

    int pairs(int k, vector arr) { unordered_set st; int n = arr.size(), c = 0; for (int i=0; i

    `

  • + 1 comment

    Nice and easy this time! First time I post a solution here, because I'm stunned it worked at the very first time, wihtout any corrections (rare case;)

    Sort + caterpillar method.

    Java solution:

        public static int pairs(int k, List<Integer> arr) {
            Collections.sort(arr);
            int a = 0;
            int b = 1;
            int count = 0;
            while (a < b && b < arr.size()) {            
                int left = arr.get(a);
                int right = arr.get(b);
                int diff = right - left;
                if (diff == k) {
                    count++;
                    b++;
                } else if (diff > k) {
                    a++;
                    if (a==b) b++;
                } else {
                    b++;
                }            
            }
    				}
            return count;
        }