[英]How to Find all Pairs in an Array of Integers Whose sum is Equal to a Given Number
[英]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);
}
}
}
}
output 是
3和8之和是11
7和4之和是11
5和6之和是11
6和5之和是11
4和7之和是11
8和3之和是11
我不想重復答案
我應該怎么辦?
您可以刪除從 map 中找到的值對,以免出現任何重復。
// code here...
if(map.containsKey(numToFind)) {
map.remove(arr[j]);
map.remove(numToFind);
// print
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.