You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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;
}
};
Given an array
arr
of integers, check if there exist two indicesi
andj
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除外,要避免这种特殊情况,需要加上检测,参见代码如下:
解法一:
我们也可以只遍历数组一遍,由于只遍历一遍,就需要同时检测倍数和半数,这里只要使用 HashSet 就可以了。对于遍历到的数字,检测倍数和半数是否存在,存在就返回 true,注意检测半数的时候要先检测该数字是否可以被2整除。若没有找到倍数或者半数,就把当前数字加入 HashSet 即可,参见代码如下:
解法二:
Github 同步地址:
#1346
类似题目:
Two Sum
Keep Multiplying Found Values by Two
参考资料:
https://leetcode.com/problems/check-if-n-and-its-double-exist
https://leetcode.com/problems/check-if-n-and-its-double-exist/solutions/503441/java-python-3-hashset-w-analysis/
https://leetcode.com/problems/check-if-n-and-its-double-exist/solutions/504918/java-easy-5-line-solution-with-explanation/
LeetCode All in One 题目讲解汇总(持续更新中...)
(欢迎加入博主的知识星球,博主将及时答疑解惑,并分享刷题经验与总结,快快加入吧~)
喜欢请点赞,疼爱请打赏❤️~.~
微信打赏
|
Venmo 打赏
---|---
The text was updated successfully, but these errors were encountered: