Thursday, February 4, 2021

How to find Pair of two sum element equivalent to given key less than N square time complexity


  
public class SumPair {

	public static void main(String[] args) {
		int arr[] = {5,7,8,3,1,4,6,9,2}; 
		int n = 12; 
		findPair(arr,n);

	}

	private static void findPair(int[] arr, int n) {
		ArrayList<Integer> numbers = new ArrayList<>();
		boolean status = false;
		for(int num : arr) {
			
			int anotherNumber = (n-num);
			if(numbers.contains(anotherNumber) && (anotherNumber+num) == n) {
				status=true;
				System.out.println("Pair Found: "+"( "+anotherNumber+", "+ num+" )"); 
			}
			numbers.add(num);
		}
		if(!status)
			System.out.print("No such pair");
	}

}

Output:- 

Pair Found: ( 5, 7 )
Pair Found: ( 8, 4 )
Pair Found: ( 3, 9 )

No comments:

Post a Comment

How to find middle node of LinkedList without using extra memory in java

To find the middle node of a LinkedList without using extra memory in Java, you can use the "tortoise and hare" algorithm. This al...