1 분 소요

Question

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).

리스트의 요소들 중에, (한 요소)*2를 한 값이 리스트에 포함되어있으면 True, 아니면 False를 반환하는 문제였다.

Example

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

Constraints

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

Solution

class Solution:
    def checkIfExist(self, arr: List[int]) -> bool:
        
        if arr.count(0)>=2: # 0이 2개 이상이면 무조건 True
            return True
        else: # 0이 없거나 1개일 때
            for x in arr:
                if x*2 in arr:
                    if x!=0: # 0*2=0 이므로 x가 0이 아닐때만 True
                        return True
            return False
       
  • 직접 푼 풀이이다.
  • 0만 신경써서 경우를 나누면 쉬운 문제였다.
  • 0이 2개 이상 있으면 0*2=0 이므로 무조건 True이다.
  • 0이 없거나 1개 있을 때에는 for문으로 리스트를 돌면서 두 배 한 값이 리스트에 있는지 확인한다.

끄적

  • arr.count(0)으로 리스트에서 0의 개수를 카운트 할 수 있다.


💛 개인 공부 기록용 블로그입니다. 👻

맨 위로 이동하기