Guest User

Untitled

a guest
Mar 24th, 2018
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.58 KB | None | 0 0
  1. public class TwoSumProblemUsingBinarySearch {
  2.  
  3. public static class Pair {
  4.  
  5. private final int x;
  6. private final int y;
  7.  
  8. public Pair(int x, int y) {
  9. this.x = x;
  10. this.y = y;
  11. }
  12.  
  13. @Override
  14. public int hashCode() {
  15. return Objects.hash(x, y);
  16. }
  17.  
  18. @Override
  19. public boolean equals(Object other) {
  20. if (other instanceof Pair) {
  21. Pair o = (Pair) other;
  22. return this.x == o.x && this.y == o.y;
  23. }
  24.  
  25. return false;
  26. }
  27.  
  28. @Override
  29. public String toString() {
  30. return String.format("(%d, %d)", x, y);
  31. }
  32. }
  33.  
  34. public static Set<Pair> findAllParis(int input[], int target) {
  35. int numbers[] = Arrays.copyOf(input, input.length);
  36. Set<Pair> pairs = new HashSet<>();
  37.  
  38. Arrays.sort(numbers);
  39.  
  40. for (int low = 0, high = input.length - 1; low < high; ) {
  41. int sum = input[low] + input[high];
  42.  
  43. if (sum > target) {
  44. high--;
  45. } else if (sum < target) {
  46. low++;
  47. } else {
  48. pairs.add(new Pair(input[low], input[high]));
  49. high--;
  50. low++;
  51. }
  52. }
  53.  
  54. return pairs;
  55. }
  56. }
  57.  
  58. @Test
  59. public void findAllParis() throws Exception {
  60.  
  61. System.out.println(TwoSumProblemUsingBinarySearch.findAllParis(new int[]{-2, -1, -1, 5, 7, 7, 7, 7, 8}, 7));
  62. assertEquals(1, TwoSumProblemUsingBinarySearch.findAllParis(new int[]{-2, -1, -1, 5, 7, 7, 7, 7, 8}, 7).size());
  63. }
Add Comment
Please, Sign In to add comment