[英]finding all pairs of numbers in an array whose sum equals a given number?
Write a program that passes in an array and will then output:编写一个程序,传入一个数组,然后输出:
1) all pairs that sum up to 10. 2) all unique pairs that sum to 10, no duplicates. 1) 总和为 10 的所有对。 2) 总和为 10 的所有唯一对,没有重复。 3) all unique pairs that sum to 10, no duplicates or reverse pairs. 3) 总和为 10 的所有唯一对,没有重复或反向对。
I have the bellow so far but it only prints the following:到目前为止,我有波纹管,但它只打印以下内容:
(1, 9) (1, 9) (4, 6) (4, 6) (5, 5) (5, 5) (1, 9) (1, 9) (4, 6) (4, 6) (5, 5) (5, 5)
public class SumOfPairs {
public void pairedElements(int arr[], int sum)
{
int low = 0;
int high = arr.length -1;
while (low < high) {
if (arr[low] + arr[high] == sum) {
System.out.println(" ("+ arr[low] + ", " + arr[high] + ")");
}
if (arr[low] + arr[high] > sum) {
high--;
}
else {
low++;
}
}
}
public static void main(String[] args)
{
int arr[] = {1, 1, 2, 4, 4, 5, 5, 5, 6, 7, 9};
Arrays.sort(arr);
SumOfPairs sp = new SumOfPairs();
sp.pairedElements(arr, 10);
}
You can use nested for loops.您可以使用嵌套的 for 循环。 In outer loop you can iterate from 0 up to the last but one.在外循环中,您可以从 0 迭代到最后一个。 In inner loop you can iterate from outer index + 1 up to the last element.在内部循环中,您可以从外部索引 + 1 迭代到最后一个元素。 Something like this:像这样的东西:
for(int i = 0; i < arr.length -1; i++){
for(int j = i + 1; j < arr.length; j++){
if(arr[i] + arr[j] == 10){
//do something
}
}
}
As stated above use a nested for loop to find your pairs.如上所述,使用嵌套的 for 循环来查找您的配对。 To find duplicates or Unique pairs i would store them in a list and check the list for instances of a value.要查找重复项或唯一对,我会将它们存储在列表中并检查列表中的值实例。
public void pairedElement(int [] arr, sum){
List<String> pairs = new ArrayList<>();
for(int x : arr){
for(int y : arr){
if(x + y == sum)
pairs.add("(" + x + "," + y + ")");
}
}
//to print all of the values:
pairs.foreach(x -> System.out.println(x));
To print the unique/duplicate pairs only id recommend checking out this Specifically the second answer will give you an idea of how to get 2 collections, one containing the unique items from the entire list (pairs) and the other containing values that are duplicates in the original list.要打印唯一/重复对,只有 id 建议检查这个特别是第二个答案将让您了解如何获取 2 个集合,一个包含整个列表(对)中的唯一项,另一个包含重复的值原始列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.