Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions DuosForSums.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import java.util.Arrays;

public class DuosForSums {

public static void main(String[] args) {
int[] initArr = {1, 3, 5, -2, 6, 0, -3, -1, 7, 2};
int sumNum = 5;
group(initArr, sumNum);
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What if initArr = {5, 5, 5, 5, 5, 5, 5, 5, 5, 5}; sumNum = 10;? Will it show all pairs (45)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Only unique pairs [[5, 5], [5, 5], [5, 5], [5, 5], [5, 5]]

Copy link
Copy Markdown

@malvitvik malvitvik Jul 19, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How many unique pairs has my example?) BTW unique - when a[i] is included only once in resulted array, right?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

unique means, if a number is already used then it is out and not used anymore


}

private static void group(int[] arr, int x) {
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

a little bit hard to understand but this is good enough for the current level. please take into account array could be created in this way new int[]{5,5}

Arrays.sort(arr);

int[][] tmp = new int[arr.length][2];

int first = 0;
int last = arr.length - 1;

int i = 0;

while (first < last) {

int sumTmp = arr[first] + arr[last];
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sumTmp the local variable is redundant

if (sumTmp == x) {
tmp[i][0] = arr[first];
tmp[i][1] = arr[last];
first++;
last--;
i++;
} else {
if (sumTmp < x) first++;
else last--;
}
}

int[][] pairs = new int[i][2];
for (int g = 0; g < i; g++) {
if (tmp[g][0] + tmp[g][1] == x) {
pairs[g][0] = tmp[g][0];
pairs[g][1] = tmp[g][1];
} else break;
}

System.out.println(Arrays.deepToString(pairs));

}

}