Find Pair in array equal to target


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import java.util.HashSet;
import java.util.Set;

class FindPairs {

 public static void main(String[] args) {
  FindPairs obj = new FindPairs();
  int[] arr1 = { 22, 1, 2, 3, 4, 5, 6, -1, 7, 9, 3, 15 };
  obj.getPairs1(arr1, 6);

 }

 private void getPairs1(final int[] input,  int sum) {
  System.out.println(" Array is: 22,  1, 2, 3,  4, 5, 6, -1,  7, 9, 3, 15 and  sum=6");
  Set<integer> set = new HashSet(input.length);
  for (int i = 0; i &lt; input.length; i++) {
   if (set.contains(sum - input[i])) {
    System.out.println("(" + input[i] + ", " + (sum - input[i]) + ") ");
   } else {
    set.add(input[i]);

   }

  }

 }
}
// Output: // Array is: 22, 1, 2, 3, 4, 5, 6, -1, 7, 9, 3, 15 and sum=6 <\br> // (4, 2) // (5, 1) // (7, -1) // (3, 3)

No comments:

Post a Comment