LeetCode-Nとその二重が存在するかどうかを確認します(検索中)

問題:配列が与えられたとき、配列にNと2 * Nが存在するかどうかを見つけることの問題

LeetCode-Nとその二重が存在するかどうかを確認するで問題を解いて見ることができます。

Example

Ex 1.

Input: arr = [10,2,5,3]
Output: true
Explanation: N = 10 is the double of M = 5,that is, 10 = 2 * 5.

Ex 2.

Input: arr = [7,1,14,11]
Output: true
Explanation: N = 14 is the double of M = 7,that is, 14 = 2 * 7.

Constraints

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

Soultion

  1. 1つのfor文でHashMapにNの2倍数をkeyで、IndexをValueに保存
  2. 1つのfor文でHashMapにNが存在するかどうかを確認し、MapにNがある場合Nの2倍数がarrに存在するということを意味
  3. 0の場合は、2の倍数も0である。このような場合、Mapから戻されるIndexで同じオブジェクトかどうか
  4. O(2n)で処理
class Solution {
	public boolean checkIfExist(int[] arr) {
        HashMap<Integer, Integer> hash = new HashMap<>();
        for (int i=0; i < arr.length; i++) {
        	hash.put(arr[i]*2, i);
        }
        for (int i=0; i < arr.length; i++) {
        	Integer index = hash.get(arr[i]);
        	if (index != null && index != i) {
        		return true;
        	}
        }
        return false;
    }
}
codechachaCopyright ©2019 codechacha