Guest User

Untitled

a guest
Mar 22nd, 2018
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.84 KB | None | 0 0
  1. public int findKComplLinearTimeLinearSpace(int[] arr, int K) {
  2. int count = 0;
  3.  
  4. // Let's store every item in a hashmap, key is the array element
  5. // value is the number of time the value occurs in the array
  6. HashMap<Integer, Integer> occurrencies = new HashMap<Integer, Integer>();
  7.  
  8. // Time: O(N)
  9. // HashMap has constant access time
  10. for (int i : arr) {
  11. if (occurrencies.get(i) == null) occurrencies.put(i, 1);
  12. else occurrencies.put(i, occurrencies.get(i) + 1);
  13. }
  14.  
  15. // Now let's traverse the hashmap and find out if for each key
  16. // one or more complementary values exists in the HashMap
  17. // Time: O(N)
  18. Set<Integer> keys = occurrencies.keySet();
  19. for (Integer key : keys) {
  20. int needed = K - key;
  21. if (occurrencies.containsKey(needed)) {
  22. count += occurrencies.get(key) * occurrencies.get(needed);
  23. }
  24. }
  25.  
  26. return count;
  27. }
Add Comment
Please, Sign In to add comment