Last updated: Oct 30, 2022
Difficulty | Runtime | Faster_than | Memory | Lesser_than |
---|---|---|---|---|
easy | 116 ms | 24.24 % | 43.8 mb | 44.36 % |
Difficulty : easy
Runtime : 116 ms Faster than 24.24 %
Memory : 43.8 mb Lesser than 44.36 %
1346. Check If N and Its Double Exist
Given an array arr of integers, check if there exist 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: For i = 0 and j = 2, arr[i] == 10 == 2 _ 5 == 2 _ arr[j] Example 2:
Input: arr = [3,1,7,11] Output: false Explanation: There is no i and j that satisfy the conditions.
Constraints:
- 2 <= arr.length <= 500
- -10^3 <= arr[i] <= 10_3
Solution:
/**
* @param {number[]} arr
* @return {boolean}
*/
var checkIfExist = function(arr) {
arr.sort((a, b) => a - b);
var res;
for (var i = 0; i < arr.length; i++) {
res = search(arr, arr[i] * 2);
if (res != i && res != -1) {
return true;
}
}
return false;
};
var search = function (arr, target) {
var l = 0;
var r = arr.length - 1;
while (l <= r) {
var m = ((r + l) / 2) ^ 0;
if (arr[m] == target) {
return m;
} else if (arr[m] > target) {
r = m - 1;
} else {
l = m + 1;
}
}
return -1;
};