FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
Java/Others/TwoPointers.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
/
TwoPointers.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
50 lines (43 loc) · 1.32 KB
Breadcrumbs
Java
/
Others
/
TwoPointers.java
Copy path
File metadata and controls
50 lines (43 loc) · 1.32 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
48
49
50
package
Others
;
import
java
.
util
.
Arrays
;
/**
* The two pointer technique is a useful tool to utilize when searching for pairs in a sorted array.
*
* <p>link: https://www.geeksforgeeks.org/two-pointers-technique/
*/
class
TwoPointers
{
public
static
void
main
(
String
[]
args
) {
int
[]
arr
= {
10
,
20
,
35
,
50
,
75
,
80
};
int
key
=
70
;
assert
isPairedSum
(
arr
,
key
);
/* 20 + 60 == 70 */
arr
=
new
int
[] {
1
,
2
,
3
,
4
,
5
,
6
,
7
};
key
=
13
;
assert
isPairedSum
(
arr
,
key
);
/* 6 + 7 == 13 */
key
=
14
;
assert
!
isPairedSum
(
arr
,
key
);
}
/**
* Given a sorted array arr (sorted in ascending order). Find if there exists any pair of elements
* such that their sum is equal to key.
*
* @param arr the array contains elements
* @param key the number to search
* @return {@code true} if there exists a pair of elements, {@code false} otherwise.
*/
private
static
boolean
isPairedSum
(
int
[]
arr
,
int
key
) {
/* array sorting is necessary for this algorithm to function correctly */
Arrays
.
sort
(
arr
);
int
i
=
0
;
/* index of first element */
int
j
=
arr
.
length
-
1
;
/* index of last element */
while
(
i
<
j
) {
if
(
arr
[
i
] +
arr
[
j
] ==
key
) {
return
true
;
}
else
if
(
arr
[
i
] +
arr
[
j
] <
key
) {
i
++;
}
else
{
j
--;
}
}
return
false
;
}
}
Back
|
FazBrowse Home
|
New Git URL