728x90
Problem
Solution
array가 주어지면 양 옆 숫자로 두 쌍을 만들었을 때 differenct parity 가 만들어지는지 확인하는 문제
우선 len(array) == 1 이면 무조건 True return
그 이후에는 둘다 홀수 or 짝수인지 확인 후 맞으면 False, 아니면 continue
굳이 동일 숫자인지 확인 안해도되었고, 홀/짝 경우로 나누지 않고 %2 나머지 값만 확인하면 된다!
def isArraySpecial(self, nums: List[int]) -> bool:
if len(nums) == 1:
return True
for i in range(len(nums)-1):
if (nums[i] % 2) == (nums[i+1] % 2):
return False
return True
Code
class Solution:
def isArraySpecial(self, nums: List[int]) -> bool:
answer = True
if len(nums) == 1:
return answer
for i in range(len(nums)-1):
if nums[i] == nums[i+1]:
return False
if nums[i] != nums[i+1]:
if nums[i]%2 == 0 and nums[i+1]%2 == 0:
return False
if nums[i]%2 != 0 and nums[i+1]%2 != 0:
return False
return answer
Complexity
Time Complexity
for문을 array 길이만큼 1번만 순회했으므로 O(n)
Space Complexity
추가 메모리나 변수를 사용하지 않음. 단순 answer 변수만 사용했으므로 O(1)
728x90
'코딩 테스트' 카테고리의 다른 글
[LeetCode] 1752. Check if Array Is Sorted and Rotated (Python) (0) | 2025.02.02 |
---|---|
[LeetCode] 637. Average of Levels in Binary Tree (Python) (0) | 2025.02.01 |
[LeetCode] 66.Plus One (Python) (0) | 2025.01.31 |
[LeetCode] 125.Valid Palindrome (Python) (0) | 2025.01.31 |
[LeetCode] 1. Two Sum (Python) (0) | 2025.01.30 |
댓글