【2020-02-11】1346. Check If N and Its Double Exist

 

更多LeetCode解題詳解git

 

Easygithub

Given an array arr of integers, check if there exists two integers N and M such that N is the double of M ( i.e. N = 2 * M).數組

More formally check if there exists two indices i and j such that :ui

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

Example 1: Input: arr = [10,2,5,3] Output: true Explanation: N = 10 is the double of M = 5,that is, 10 = 2 * 5. Example 1: Input: arr = [10,2,5,3] Output: true Explanation: N = 10 is the double of M = 5,that is, 10 = 2 * 5.
Example 2: Input: arr = [7,1,14,11] Output: true Explanation: N = 14 is the double of M = 7,that is, 14 = 2 * 7. Example 2: Input: arr = [7,1,14,11] Output: true Explanation: N = 14 is the double of M = 7,that is, 14 = 2 * 7.
Example 3: Input: arr = [3,1,7,11] Output: false Explanation: In this case does not exist N and M, such that N = 2 * M. Example 3: Input: arr = [3,1,7,11] Output: false Explanation: In this case does not exist N and M, such that N = 2 * M.

Constraints:spa

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

 

 


 

 

有近半月沒有作題了,先作道簡單題吧。給一個數字數組,判斷數組中是否存在一個數是另外一數的2倍大小。orm

  • force暴力拆解法
  • map + 兩次循環
  • set + 一次循環

force暴力拆解法

暴力拆解法就是雙次循環,每次對兩個值進行判斷leetcode

  • 複雜度分析
    • 時間複雜度:O(N^2), N是數組長度
    • 空間複雜度:O(N)
/** * @param {number[]} arr * @return {boolean} */ var checkIfExist = function(arr) { for (let i = 0; i < arr.length; i++) { for (let j = 0; j < arr.length; j++) { if (arr[i] == 2 * arr[j] && i !== j) return true } } return false }; 

map

經過使用map,存儲arr的值和下標。在第二次循環arr時,經過比較該值的雙倍是否在map中存在,若是存在,而且下標不一致,就返回true。get

  • 複雜度分析
    • 時間複雜度:O(N), N是數組長度
    • 空間複雜度:O(N)
/** * @param {number[]} arr * @return {boolean} */ var checkIfExist = function(arr) { let map = new Map() for (let i = 0; i < arr.length; i++) { map.set(arr[i], i) } for (let i = 0; i < arr.length; i++) { let double = arr[i] * 2 if (map.has(double) && map.get(double) !== i) return true } return false }; 

set

循環時判斷,該值的一半或者2倍是否在set中存在,若是存在,就返回true,若是不在,則使用set來存儲該循環中值。

  • 複雜度分析
    • 時間複雜度:O(N), N是數組長度
    • 空間複雜度:O(N)
/** * @param {number[]} arr * @return {boolean} */ var checkIfExist = function(arr) { let set = new Set() for (let i of arr) { if (set.has(2*i) || i % 2 == 0 && set.has(Math.floor(i / 2))) return true set.add(i) } return false };

來源

相關文章
相關標籤/搜索