알고리즘

Check If N and Its Double Exist

JUNGKEUNG 2021. 7. 19. 06:01

정수 배열이 주어진 경우에, 특정 원소 N에 대하여 그것의 Double값을 가진 원소가 있는지 여부를 체크해주는 문제이다.

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 :

 

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

 

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 3:

Input: arr = [3,1,7,11] Output: false Explanation: In this case does not exist N and M, such that N = 2 * M.

 

class Jk_leetcode_arrays101_3250 {
    public boolean checkIfExist(int[] arr) {
       // 같은 원소는 확인할 필요가 없으니 Set객체를 만든다
        Set<Integer> set = new HashSet<> ();
        //배열에 대한 Loop를 돌린다
        for (Integer num : arr) {
            // Set객체에 target element에 대한 곱하기2나 나누기2 element가 없다면 Set에 밀어넣어준다
            if (set.contains(num * 2) || (num % 2 == 0 && set.contains(num / 2))) {
                //있다면 바로 true를, Loop끝까지 없다면 false를 리턴해주기로 했다.
                return true;
            }

            set.add(num);
        }
        return false;
    }
}