[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


类似题目:

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 题目讲解汇总(持续更新中...)

posted @   Grandyang  阅读(219)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 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 包围区域
Fork me on GitHub

喜欢请打赏

扫描二维码打赏

Venmo 打赏

点击右上角即可分享
微信分享提示