[LeetCode] 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
这道题给了一个整型数组,让检测是否有一个数字和其倍数同时存在的情况。一看到这道题博主就想到了 Two Sum,身为 LeetCode 的开山之作,简直经典到无与伦比,其变型题目也有很多,这道题就是其中之一。万变不离其宗,解法还是大同小异,使用一个 HashMap 来建立数字和其坐标的映射,这样再次遍历每个数字,就可以直接在 HashMap 中查找其倍数是否存在,别忘了比较找到的数字和当前数字的坐标,要确保不是一个数字,一般情况下数字和其倍数不会相同,但是0除外,要避免这种特殊情况,需要加上检测,参见代码如下:
解法一:
class Solution {
public:
bool checkIfExist(vector<int>& arr) {
unordered_map<int, int> m;
for (int i = 0; i < arr.size(); ++i) {
m[arr[i]] = i;
}
for (int i = 0; i < arr.size(); ++i) {
int t = arr[i] * 2;
if (m.count(t) && i != m[t]) return true;
}
return false;
}
};
我们也可以只遍历数组一遍,由于只遍历一遍,就需要同时检测倍数和半数,这里只要使用 HashSet 就可以了。对于遍历到的数字,检测倍数和半数是否存在,存在就返回 true,注意检测半数的时候要先检测该数字是否可以被2整除。若没有找到倍数或者半数,就把当前数字加入 HashSet 即可,参见代码如下:
解法二:
class Solution {
public:
bool checkIfExist(vector<int>& arr) {
unordered_set<int> st;
for (int num : arr) {
if (st.count(num * 2) || (num % 2 == 0 && st.count(num / 2))) return true;
st.insert(num);
}
return false;
}
};
Github 同步地址:
https://github.com/grandyang/leetcode/issues/1346
类似题目:
Keep Multiplying Found Values by Two
参考资料:
https://leetcode.com/problems/check-if-n-and-its-double-exist
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
2019-06-05 [LeetCode] 898. Bitwise ORs of Subarrays 子数组按位或操作
2017-06-05 [LeetCode] Design In-Memory File System 设计内存文件系统
2016-06-05 [LintCode] Happy Number 快乐数
2015-06-05 [LeetCode] 130. Surrounded Regions 包围区域