Python Algorithm
LeetCode
2553. Separate the Digits in an Array
- Given an array of positive integers nums, return an array answer that consists of the digits of each integer in nums after separating them in the same order they appear in nums.
- To separate the digits of an integer is to get all the digits it has in the same order.
- For example, for the integer 10921, the separation of its digits is [1,0,9,2,1].
- Constraints:
- 1 ≤ nums.length ≤ 1000
- 1 ≤ nums[i] ≤ 105
class Solution:
def separateDigits(self, nums: List[int]) -> List[int]:
answer = []
for num in nums:
num_str = str(num)
for c in num_str:
# 숫자를 문자로 바꿔서 한 글자씩 읽어오는데 성공!
# 이를 다시 숫자로 바꿔서 answer에 append
answer.append(int(c))
return answer
class Solution:
def separateDigits(self, nums: List[int]) -> List[int]:
answer = []
for i in nums:
s = str(i)
for j in s:
answer.append(int(j))
return answer
2206. Divide Array Into Equal Pairs
- You are given an integer array nums consisting of 2 * n integers.
- You need to divide nums into n pairs such that:
- Each element belongs to exactly one pair.
- The elements present in a pair are equal.
- Return true if nums can be divided into n pairs, otherwise return false.
- Constraints:
- nums.length = 2 ⨉ n
- 1 ≤ n ≤ 500
- 1 ≤ nums[i] ≤ 500
from collections import Counter
class Solution:
def divideArray(self, nums: List[int]) -> bool:
nums_counter = Counter(nums)
answer = True
for key, value in nums_counter.items():
# 만약 value가 2로 나누어 떨어지지 않는다면
# answer를 False로 만들고 break
if value % 2 != 0:
answer = False
break
return answer
from collections import Counter
class Solution:
def divideArray(self, nums: List[int]) -> bool:
answer = True
nums_dict = Counter(nums)
for i in nums_dict.values():
if i % 2 != 0:
answer = False
return answer
https://leetcode.com/problems/separate-the-digits-in-an-array/
https://leetcode.com/problems/divide-array-into-equal-pairs/
'지난 공부기록 > 알고리즘 풀이' 카테고리의 다른 글
| Python - Algorithm #6 (0) | 2024.06.18 |
|---|---|
| Python - Algorithm #5 (0) | 2024.06.17 |
| Python - Algorithm #3 (0) | 2024.06.11 |
| Python - Algorithm #2 (0) | 2024.06.10 |
| Python - Algorithm #1 (0) | 2024.06.07 |