Given an array arr
of integers, check if there exists two integers N
and M
such that N
is the double of M
( i.e. N = 2 * M
).
More formally check if there exists two indices i
and j
such that :
i != j
0 <= i, j < arr.length
arr[i] == 2 * arr[j]
Example 1:
Input: arr = [10,2,5,3] Output: true Explanation: N= 10
is the double of M= 5
,that is,10 = 2 * 5
.
Example 2:
Input: arr = [7,1,14,11] Output: true Explanation: N= 14
is the double of M= 7
,that is,14 = 2 * 7
.
Example 3:
Input: arr = [3,1,7,11] Output: false Explanation: In this case does not exist N and M, such that N = 2 * M.
Constraints:
2 <= arr.length <= 500
-10^3 <= arr[i] <= 10^3
class Solution:
def checkIfExist(self, arr: List[int]) -> bool:
map = defaultdict(int)
for i, num in enumerate(arr):
map[num] = i
for i, num in enumerate(arr):
if num << 1 in map and i != map[num << 1]:
return True
return False
class Solution {
public boolean checkIfExist(int[] arr) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < arr.length; i++) {
map.put(arr[i], i);
}
for (int i = 0; i < arr.length; i++) {
if (map.containsKey(arr[i] << 1) && i != map.get(arr[i] << 1))
return true;
}
return false;
}
}
function checkIfExist(arr: number[]): boolean {
for (let i = arr.length - 1; i >= 0; --i) {
let cur = arr[i];
let t1 = 2 * cur;
if (arr.includes(t1) && arr.indexOf(t1) != i) {
return true;
}
let t2 = cur >> 1;
if (cur % 2 == 0 && arr.includes(t2) && arr.indexOf(t2) != i) {
return true;
}
}
return false;
}
class Solution {
public:
bool checkIfExist(vector<int>& arr) {
unordered_map<int, int> map;
for (int i = 0; i < arr.size(); ++i) {
map[arr[i]] = i;
}
for (int i = 0; i < arr.size(); ++i) {
if (map.find(arr[i] * 2) != map.end() && i != map[arr[i] * 2]) {
return true;
}
}
return false;
}
};