Python/algorithm(22)
-
[Leetcode] 1528. Shuffle String
Problem 이번 문제는 s 라는 문자열이 주어지고 indices에 s 문자열 각자리의 알맞는 인덱스가 들어가있고 정렬해서 return 해주는 문제이다. 나의 풀이 class Solution: def restoreString(self, s: str, indices: List[int]) -> str: res = '' zipped = sorted(zip(indices, s), key=lambda x: x[0]) for idx,char in zipped: res += char return res zip으로 두개를 묶고 , 인덱스를 기준으로 정렬한 뒤에 res에 더해주고 return 해 주었어용 다른 사람의 풀이 두가지를 보자 class Solution: def restoreString(self, s: str..
2023.01.12 -
[Leetcode] 2236. Root Equals Sum of Children
Problem 이번 문제는 이진 트리를 주고 ? 루트, 왼쪽, 오른쪽 자식 값이 존재한다. left , right 의 합이 root와 같으면 True 아니면 false를 return 한다. 나의 풀이 # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def checkTree(self, root: Optional[TreeNode]) -> bool: #print(root.left, root.left.val) #print(root.right,..
2023.01.11 -
[Leetcode] 1365. How Many Numbers Are Smaller Than the Current Number
Problem 이번 문제는 nums 각 값을 nums의 다른 값과 비교하여 작은값의 갯수를 배열로 return 해주는 문제이다 나의 풀이 class Solution: def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]: res = list() for i in nums: cnt = 0 for j in nums: if i > j: cnt += 1 res.append(cnt) return res 열심히 짱구를 굴려봤는데 for 두번을 사용하지않고는 문제가 풀리지 않았다. 다른 사람의 풀이 class Solution: def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]: l1 = ..
2023.01.05 -
[Leetcode] 1281. Subtract the Product and Sum of Digits of an Integer
Problem 이번 문제는 주어진 수 n의 각 자리수를 곱한 값에 더한 값을 뺀 값을 결과로 낸다 나의 풀이 from functools import reduce class Solution: def subtractProductAndSum(self, n: int) -> int: a = list(map(int,str(n))) return reduce((lambda x,y: x*y), a) - sum(a) list로 바꿔주고 functools 에 있는 reduce를 사용하여 문제를 풀었다 더한 값의 경우는 sum 을 사용하면 되지만 곱한 값의 경우는 sum 같은 부분이 없다 ㅠㅠ reduce(sum,[1,2,3,4,5,6])
2023.01.04 -
[Leetcode] 1431. Kids With the Greatest Number of Candies
Problem 이번 문제는 캔디갯수를 가진 배열 candies 와 , 더할 캔디 extraCandies를 주고 candies 각 캔디 갯수에 extraCandies를 더한값이 candies의 최대 값이면 True, 아니면 False로 바꾸어 반환한다 나의 풀이 class Solution: def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]: return [i+extraCandies>=max(candies) for i in candies] i+extraCandies 가 candies의 최대값과 크거나 같으면 True , 아니면 False 가 나오게 문제를 풀고 리스트 컴프리헨션을 사용했다
2023.01.02 -
[Leetcode] 2413. Smallest Even Multiple
Problem 이번 문제는 어렵게 써놧지만 최소공배수를 구하는 문제이다 나의 풀이 class Solution: def smallestEvenMultiple(self, n: int) -> int: import math return math.lcm(n,2) # for i in range(max(a, b), (a * b) + 1): # if i % a == 0 and i % b == 0: # return i 파이썬 MATH에 있는 LCM을 사용하여서 문제를 풀었고 아래에 있는 풀이가 최소 공배수를 푸는 공식이다.
2022.12.31