Target Sun Pair [codingblocks]
Take as input N, the size of array. Take N more inputs and store that in an array. Take as input “target”, a number. Write a function which prints all pairs of numbers which sum to target.
Input Format
The first line contains input N. Next N lines contains the elements of array and (N+1)th line contains target number.
Constraints
Length of the arrays should be between 1 and 1000.
Output Format
Print all the pairs of numbers which sum to target. Print each pair in increasing order.
Sample Input
5
1
3
4
2
5
5
Sample Output
1 and 4
2 and 3
Explanation
Find any pair of elements in the array which has sum equal to target element and print them.
Java Code:
IDE code: https://ide.geeksforgeeks.org/Wl02iwmoD1
/* Amit Kumar 04-12-2020 IDE Code: https://ide.geeksforgeeks.org/Wl02iwmoD1 */ package array; import java.util.Scanner; public class Array_TargetSumPair { public static Scanner scanner = new Scanner(System.in); public static void main(String [] args) { int arrSize = scanner.nextInt(); int [] arr = new int[arrSize]; for (int i=0; i<arrSize; i++) { arr[i] = scanner.nextInt(); } int targetSum = scanner.nextInt(); bubbleSort(arr); printTargetSum(arr, targetSum); } public static void printTargetSum(int[] arr, int targetSum) { int head, tail; head = 0; tail = arr.length-1; while (head < tail) { if (arr[head] + arr[tail] == targetSum) { System.out.println(arr[head] + " and " + arr[tail]); head++; tail--; } else if (arr[head] + arr[tail] > targetSum) { tail--; } else { head++; } } } public static void bubbleSort(int[] arr) { for (int i=0; i<arr.length; i++) { for (int j=0; j<arr.length-i-1; j++) { if (arr[j] > arr[j+1]) { int temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } } } }
Comments
Post a Comment