Skip to content

Latest commit

 

History

History
139 lines (105 loc) · 3.39 KB

File metadata and controls

139 lines (105 loc) · 3.39 KB

English Version

题目描述

给你一个整数数组 arr,请你检查是否存在两个整数 NM,满足 N 是 M 的两倍(即,N = 2 * M)。

更正式地,检查是否存在两个下标 ij 满足:

  • i != j
  • 0 <= i, j < arr.length
  • arr[i] == 2 * arr[j]

 

示例 1:

输入:arr = [10,2,5,3]
输出:true
解释:N = 10 是 M = 5 的两倍,即 10 = 2 * 5 。

示例 2:

输入:arr = [7,1,14,11]
输出:true
解释:N = 14 是 M = 7 的两倍,即 14 = 2 * 7 

示例 3:

输入:arr = [3,1,7,11]
输出:false
解释:在该情况下不存在 N 和 M 满足 N = 2 * M 。

 

提示:

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

解法

Python3

class Solution:
    def checkIfExist(self, arr: List[int]) -> bool:
        map = collections.defaultdict(int)
        for i, num in enumerate(arr):
            map[num] = i
        for i, num in enumerate(arr):
            if num << 1 in map and i != map[num << 1]:
                return True
        return False

Java

class Solution {
    public boolean checkIfExist(int[] arr) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < arr.length; i++) {
            map.put(arr[i], i);
        }
        for (int i = 0; i < arr.length; i++) {
            if (map.containsKey(arr[i] << 1) && i != map.get(arr[i] << 1))
                return true;
        }
        return false;
    }
}

TypeScript

function checkIfExist(arr: number[]): boolean {
    for (let i = arr.length - 1; i >= 0; --i) {
        let cur = arr[i];
        let t1 = 2 * cur; 
        if (arr.includes(t1) && arr.indexOf(t1) != i) {
            return true;
        }
        let t2 = cur >> 1;
        if (cur % 2 == 0 && arr.includes(t2) && arr.indexOf(t2) != i) {
            return true;
        }
    }
    return false;
};

C++

class Solution {
public:
    bool checkIfExist(vector<int>& arr) {
        unordered_map<int, int> map;
        for (int i = 0; i < arr.size(); ++i) {
            map[arr[i]] = i;
        }
        for (int i = 0; i < arr.size(); ++i) {
            if (map.find(arr[i] * 2) != map.end() && i != map[arr[i] * 2]) {
                return true;
            }
        }
        return false;
    }
};

...