//GitHub https://github.com/vellimole0621
LeetCode - Check If N and Its Double Exist
문제 설명
:
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]
=> 수로 이루어진 한 배열이 주어지고. 배열의 요소 중 하나가 다른 한 요소의 두 배한 것과 값이 같은게 있는지 확인하라.
내 풀이
:
If 요소 중 0인 요소가 두 개 이상있으면 True
elif 이중반복문으로 각 요소 별로 직접 비교해서 확인
# Check If N and Its Double Exist
# https://leetcode.com/explore/learn/card/fun-with-arrays/527/searching-for-items-in-an-array/3250/
class Solution:
def checkIfExist(self, arr: List[int]) -> bool:
for i in range(0, len(arr)):
for j in range(0, len(arr)):
if i != j:
if arr[j] == 0 and arr[i] == 0:
return True
elif arr[i] == arr[j] * 2:
return True
return False
더 나은 풀이
:
전체를 두 번 반복하는 이중 반복문을 쓰기 보다는 range(0, len(arr)) 안에 range(i, len(arr))을 두고.
if arr[i] == arr[j] * 2 or arr[j] == arr[i] * 2 로 두었으면 불필요한 반복을 줄일 수 있다.
'프로그래밍 > Python' 카테고리의 다른 글
[파이썬 Python/알고리즘] LeetCode - Remove Duplicates from Sorted Array (0) | 2023.09.18 |
---|---|
[파이썬 Python/알고리즘] LeetCode - Replace Elements with Greatest Element on Right Side (0) | 2023.09.17 |
[파이썬 Python/알고리즘] LeetCode - Remove Element (0) | 2023.09.07 |
[파이썬 Python/알고리즘] LeetCode - Merge Sorted Array (0) | 2023.09.05 |
[파이썬 Python/알고리즘] LeetCode - Duplicate Zeros (0) | 2023.09.05 |