[LeetCode] Check If N and Its Double Exist

아르당·2026년 4월 23일

LeetCode

목록 보기
279/303
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

정수 배열 arr가 주어졌을 때, 다음 조건을 만족하는 두 인덱스 i와 j가 존재하는지 확인해라.

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

Example

#1
Input: arr = [10, 2, 5, 3]
Output: true
Explanation: i = 0과 j = 2에 대해, arr[i] == 10 == 2 5 == 2 arr[j]

#2
Input: arr = [3, 1, 7, 11]
Output: false
Explanation: i와 j에서 만족하는 조건이 없다.

Constraints

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

Solved

class Solution {
    public boolean checkIfExist(int[] arr) {
        HashSet<Integer> set = new HashSet<>();

        for(int num : arr){
            if(set.contains(num * 2) || (num % 2 == 0 && set.contains(num / 2))){
                return true;
            }

            set.add(num);
        }

        return false;
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글