|
| 1 | +/** |
| 2 | + * |
| 3 | + */ |
| 4 | +package com.visa.practice; |
| 5 | + |
| 6 | +import java.util.HashSet; |
| 7 | +import java.util.Set; |
| 8 | + |
| 9 | +/** |
| 10 | + * @author yz09 |
| 11 | + * |
| 12 | + */ |
| 13 | +public class NumberSumMatch { |
| 14 | + |
| 15 | + /** |
| 16 | + * @param args |
| 17 | + */ |
| 18 | + public static void main(String[] args) { |
| 19 | + int[] sortedInput = { -7, -6, -5, 1, 2, 4, 4, 13, 14 }; |
| 20 | + System.out.println( |
| 21 | + "result.." + hasPairToSumInSortedArray(sortedInput, 8)); |
| 22 | + int[] unsortedInput = { 2, 1, 14, 13, 4, -7, -5, 4, -6 }; |
| 23 | + System.out.println( |
| 24 | + "result.." + hasPairToSuminUnsortedArray(unsortedInput, 8)); |
| 25 | + } |
| 26 | + |
| 27 | + public static String hasPairToSuminUnsortedArray(int[] input, |
| 28 | + int givenSum) { |
| 29 | + StringBuilder result = new StringBuilder(); |
| 30 | + Set<Integer> complimentSet = new HashSet<>(); |
| 31 | + for (int number : input) { |
| 32 | + if (complimentSet.contains(number)) { |
| 33 | + result.append((givenSum - number) + "," + number + "\n"); |
| 34 | + } else { |
| 35 | + int compliment = givenSum - number; |
| 36 | + complimentSet.add(compliment); |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + return result.toString(); |
| 41 | + } |
| 42 | + |
| 43 | + public static String hasPairToSumInSortedArray(int[] input, int givenSum) { |
| 44 | + StringBuilder result = new StringBuilder(); |
| 45 | + int low = 0; |
| 46 | + int high = input.length - 1; |
| 47 | + while (low < high) { |
| 48 | + int sum = input[low] + input[high]; |
| 49 | + if (givenSum == sum) { |
| 50 | + result.append(input[low] + "," + input[high] + "\n"); |
| 51 | + low++; |
| 52 | + high--; |
| 53 | + } else if (givenSum > sum) { |
| 54 | + low++; |
| 55 | + } else { |
| 56 | + high--; |
| 57 | + } |
| 58 | + } |
| 59 | + return result.toString(); |
| 60 | + |
| 61 | + } |
| 62 | + |
| 63 | +} |
0 commit comments