fork download
  1. /**
  2.  * User: uerturk
  3.  */
  4.  
  5. import java.util.*;
  6.  
  7. /**
  8.  * Input - array of integers size N, integer Threshold.
  9.  * Output - the pairs (x, y) of distinct elements with condition x + y <= Threshold.
  10.  * Is that possible to implement is with O(n) ?
  11.  */
  12. class FindPairsUnderThreshold {
  13.  
  14.  
  15. public List<Map.Entry<Integer, Set<Integer>>> solve(Integer[] integers, Integer threshold) {
  16.  
  17. // the complexity > O(n), sorted list is the key in this solution
  18. SortedSet<Integer> sortedSet = new TreeSet<Integer>();
  19.  
  20. // first put values into the sorted set
  21. for (Integer number : integers) {
  22. sortedSet.add(number);
  23. }
  24.  
  25. // then get the range from the head (smallest value) to the maximum value that satisfies the condition
  26. List<Map.Entry<Integer, Set<Integer>>> result = new ArrayList<Map.Entry<Integer, Set<Integer>>>();
  27. for (Integer number : integers) {
  28. // headSet is not inclusive, +1 is to make it include the exact sum
  29. int diff = threshold - number + 1;
  30. Set<Integer> integerIntegerSortedMap = sortedSet.headSet(diff);
  31.  
  32. Map.Entry<Integer, Set<Integer>> integerSetPair = new AbstractMap.SimpleEntry<Integer, Set<Integer>>(number, integerIntegerSortedMap);
  33. result.add(integerSetPair);
  34. }
  35. return result;
  36. }
  37.  
  38.  
  39. public static void main(String[] args) {
  40. Integer[] integers = {4, 1, 5, 2, 3, -1, 6,};
  41. Integer threshold = 4;
  42. List<Map.Entry<Integer, Set<Integer>>> solution = new FindPairsUnderThreshold().solve(integers, threshold);
  43. for (Map.Entry<Integer, Set<Integer>> entry : solution) {
  44. Integer first = entry.getKey();
  45. for (Integer second : entry.getValue()) {
  46. System.out.print("(" + first + ", " + second + "), ");
  47. }
  48. }
  49. }
  50.  
  51. }
  52.  
Success #stdin #stdout 0.08s 380160KB
stdin
Standard input is empty
stdout
(4, -1), (1, -1), (1, 1), (1, 2), (1, 3), (5, -1), (2, -1), (2, 1), (2, 2), (3, -1), (3, 1), (-1, -1), (-1, 1), (-1, 2), (-1, 3), (-1, 4), (-1, 5),