We want to quickly check if for any number in the array, its double or half (if even) also exists elsewhere in the array. Using a hash set allows for fast lookups.
By storing all numbers in a set, we can check for each number if its double or, if the number is even, its half exists in the set (excluding itself for the half case). This covers all possible pairs efficiently.
classSolution {
publicbooleancheckIfExist(int[] arr) {
Set<Integer> s =new HashSet<>();
int zeroCount = 0;
for (int x : arr) {
s.add(x);
if (x == 0) zeroCount++;
}
if (zeroCount > 1) returntrue;
for (int x : arr) {
if (x != 0 && s.contains(2 * x)) returntrue;
if (x % 2 == 0 && x != 0 && s.contains(x / 2)) returntrue;
}
returnfalse;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
funcheckIfExist(arr: IntArray): Boolean {
val s = arr.toSet()
val zeroCount = arr.count { it==0 }
if (zeroCount > 1) returntruefor (x in arr) {
if (x !=0&&2 * x in s) returntrueif (x % 2==0&& x !=0&& x / 2in s) returntrue }
returnfalse }
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution:
defcheck_if_exist(self, arr: list[int]) -> bool:
s = set(arr)
zero_count = arr.count(0)
if zero_count >1:
returnTruefor x in arr:
if x !=0and2* x in s:
returnTrueif x %2==0and x !=0and x //2in s:
returnTruereturnFalse
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
impl Solution {
pubfncheck_if_exist(arr: Vec<i32>) -> bool {
letmut s: std::collections::HashSet<i32>= arr.iter().cloned().collect();
let zero_count = arr.iter().filter(|&&x| x ==0).count();
if zero_count >1 {
returntrue;
}
for&x in&arr {
if x !=0&& s.contains(&(2* x)) {
returntrue;
}
if x %2==0&& x !=0&& s.contains(&(x /2)) {
returntrue;
}
}
false }
}