1346. Check If N and Its Double Exist
https://leetcode.com/problems/check-if-n-and-its-double-exist/
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 != j0 <= i, j < arr.lengtharr[i] == 2 * arr[j]
数组中是否存在某元素是另一个元素的二倍。遍历,hash set记录已经出现过的元素,检查set里是否有当前元素两倍或1/2的元素(且能整除)。
class Solution {
public:
bool checkIfExist(vector<int>& arr) {
unordered_set<int> s;
for (const auto a : arr) {
if (s.count(a * 2) || a % 2 == 0 && s.count(a / 2)) return true;
s.insert(a);
}
return false;
}
};Last updated
Was this helpful?