1346. 检查整数及其两倍数是否存在『简单』

题目来源于力扣(LeetCode

一、题目

1346. 检查整数及其两倍数是否存在

题目相关标签:数组

说明:

  • 2 <= arr.length <= 500
  • -10^3 <= arr[i] <= 10^3

二、解题思路

  1. 利用 Set 集合来判断某元素是否存在

  2. 遍历 arr 数组,判断当前遍历元素乘 2 或除 2 后的结果是否存在于 Set 集合中

  3. 如果当前遍历元素乘 2 或除 2 后的结果存在于 Set 集合中,说明该元素在数组中存在两倍数或该元素为某个元素的两倍数

  4. 将当前遍历元素添加到时 Set 集合中,作为后面的数组元素计算后结果的判断

三、代码实现

public static boolean checkIfExist(int[] arr) {
    // Set集合记录数组中的元素
    Set<Integer> set = new HashSet<>();
    for (int i : arr) {
        // set中已有 10 时,再出现 5 的情况
        if (set.contains(i * 2)) {
            return true;
        }
        // set中已有 5 时,再出现 10 的情况,则 i 作为除数时,i 必须为偶数
        if (i % 2 == 0 && set.contains(i / 2)) {
            return true;
        }
        // set 集合存储 arr 数组元素
        set.add(i);
    }
    return false;
}

四、执行用时

五、部分测试用例

public static void main(String[] args) {
    int[] arr = {10, 2, 5, 3};  // output:true
//    int[] arr = {7, 1, 14, 11};  // output:true
//    int[] arr = {3, 1, 7, 11};  // output:false
    boolean result = checkIfExist(arr);
    System.out.println(result);
}
原文地址:https://www.cnblogs.com/zhiyin1209/p/12906901.html