简体   繁体   中英

Find all pairs of elements from an array whose sum is equal to given number by hashmap in java

public static void main(String[] args) {
    getSum(new int[] {3,7,5,6,4,8} , 11);

}
public static void getSum (int arr [], int target) {
   /* for (int i = 0 ; i < arr.length ; i++) {
        for (int j = i+1 ; j < arr.length ; j++){
            if (arr[i] + arr[j] == 10 ) {
                System.out.println(" the Sum of  " + arr[i] + " and " + arr[j] + " is " + target);
            }
        }
    }
*/
    Map<Integer , Integer > map = new Hashtable<>() ;
    for (int i = 0 ; i < arr.length ; i++) {
        map.put(arr[i], i ) ;
    }
    //System.out.println(map);
    for (int j = 0 ; j < arr.length ; j++) {
       int numToFind = target - arr[j] ;
       if (map.containsKey(numToFind)  ) {
         System.out.println(" The Sum of  " + arr[j] + " and " + numToFind + " is " + target);

       }
    }
}

}

the output is

The Sum of 3 and 8 is 11
The Sum of 7 and 4 is 11
The Sum of 5 and 6 is 11
The Sum of 6 and 5 is 11
The Sum of 4 and 7 is 11
The Sum of 8 and 3 is 11

I dont want to repeat the answer

What should I do?

You can remove the pair of values once found from the map so that there won't be any duplicates.

// code here...
if(map.containsKey(numToFind)) {
    map.remove(arr[j]);
    map.remove(numToFind);
    // print
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM