You are viewing a single comment's thread. Return to all comments →
Nice one. Indeed can be easily done using 1 iteration in log(N) time. Slightly uglier but similar solution using Java 8:
static int pairs(int k, int[] arr) { int res = 0; Map<Integer, Integer> complements = new HashMap<>(); for (int el : arr) { if (complements.containsKey(el)) { res = res + complements.get(el); } if (el - k > 0) { complements.compute(el - k, (key, value) -> (value == null) ? 1 : value + 1); } complements.compute(el + k, (key, value) -> (value == null) ? 1 : value + 1); } return res; }
Seems like cookies are disabled on this browser, please enable them to open this website
Pairs
You are viewing a single comment's thread. Return to all comments →
Nice one. Indeed can be easily done using 1 iteration in log(N) time. Slightly uglier but similar solution using Java 8: