Sum of 2 elements in array with Target element

import java.util.HashSet;
import java.util.Set;

public class SumElements{

public static void main(String[] args) {
SumElements test = new SumElements();
int[] arr = { 2, 3, 4, 2, 1, 10, -4, 3 }; // Integer array
test.findPairs(arr, 6);
}

// The findPairs method time complexity would be O(n)
public void findPairs(int[] arr, int target) {
if (arr.length < 2) {    //Base-Case (If array length is less than 2, Just return)
return;
}
Set<Integer> set = new HashSet<Integer>(arr.length);

for (int num : arr) {
int result = target - num;
if (!set.contains(result)) {
set.add(num);
} else {
System.out.println("Pairs are: (" + num + " " + result + ")");
}
}
}

}

Time complexity: O(n)

//Output: 
//Pairs are: (4 2)
//Pairs are: (-4 10)
//Pairs are: (3 3)




No comments:

Post a Comment