[LeetCode][C++] #1346. Check If N and Its Double Exist

Newone Tsai
Nov 23, 2022

[Easy][Question]:

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
  • -103 <= arr[i] <= 103

My Solution[C++]:

[Ideas]: 這題第一直覺就是暴力解,先乘兩倍再開始一個一個找,但這樣時間複雜度是O(N^2),所以要用另一個方式

利用HashTable的unordered_set來記錄,先做乘二或除二的判斷,是否存在Set裡面,如果有就結束,如果沒有就放進去Set(打不贏就加入的概念XD)

--

--

Newone Tsai

I took the one less traveled by, and that has made all the difference.