FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
Java/Others/ThreeSum.java at master · primary-code-test/Java · GitHub
primary-code-test
Java
Repository navigation
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
Java
/
Others
/
ThreeSum.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
47 lines (38 loc) · 1.13 KB
Breadcrumbs
Java
/
Others
/
ThreeSum.java
Copy path
File metadata and controls
47 lines (38 loc) · 1.13 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package
Others
;
import
java
.
util
.
Arrays
;
import
java
.
util
.
Scanner
;
/**
* To find triplet equals to given sum in complexity O(n*log(n))
*
* <p>Array must be sorted
*
* @author Ujjawal Joshi
* @date 2020.05.18
* <p>Test Cases: Input: 6 //Length of array 12 3 4 1 6 9 target=24 Output:3 9 12 Explanation:
* There is a triplet (12, 3 and 9) present in the array whose sum is 24.
*/
class
ThreeSum
{
public
static
void
main
(
String
args
[]) {
Scanner
sc
=
new
Scanner
(
System
.
in
);
int
n
=
sc
.
nextInt
();
// Length of an array
int
a
[] =
new
int
[
n
];
for
(
int
i
=
0
;
i
<
n
;
i
++) {
a
[
i
] =
sc
.
nextInt
();
}
System
.
out
.
println
(
"Target"
);
int
n_find
=
sc
.
nextInt
();
Arrays
.
sort
(
a
);
// Sort the array if array is not sorted
for
(
int
i
=
0
;
i
<
n
;
i
++) {
int
l
=
i
+
1
,
r
=
n
-
1
;
while
(
l
<
r
) {
if
(
a
[
i
] +
a
[
l
] +
a
[
r
] ==
n_find
) {
System
.
out
.
println
(
a
[
i
] +
" "
+
a
[
l
] +
" "
+
a
[
r
]);
break
;
}
// if you want all the triplets write l++;r--; insted of break;
else
if
(
a
[
i
] +
a
[
l
] +
a
[
r
] <
n_find
)
l
++;
else
r
--;
}
}
sc
.
close
();
}
}
Back
|
FazBrowse Home
|
New Git URL