-
[leetcode 추석맞이 3문제] minimum-absolute-, differencerepeated-dna-sequences, pseudo-palindromic-paths-in-a-binary-tree
2020. 10. 1. 17:20
Minimum Absolute Difference (Dictionary 이용)
Given an array of distinct integers arr, find all pairs of elements with the minimum absolute difference of any two elements.
Return a list of pairs in ascending order(with respect to pairs), each pair [a, b] follows
- a, b are from arr
- a < b
- b - a equals to the minimum absolute difference of any two elements in arr
class Solution: def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]: #정렬을 해놓고 #두 수의 간격이 가장 작은거 = minimum absolute difference arr = sorted(arr) minNum = 10000000 #arr[i]가 10^6까지랬으니까 dic = {} #작은 값들 저장할 dic for idx in range(len(arr)-1): tmp = abs(arr[idx]-arr[idx+1]) if tmp <= minNum: minNum = tmp if tmp not in dic: print(tmp) dic[tmp] =[] dic[tmp].append([arr[idx],arr[idx+1]]) return dic[minNum]
Repeated DNA Sequences (슬라이딩 윈도우 이용)
All DNA is composed of a series of nucleotides abbreviated as A, C, G, and T, for example: "ACGAATTCCG". When studying DNA, it is sometimes useful to identify repeated sequences within the DNA.
Write a function to find all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule.
class Solution: def findRepeatedDnaSequences(self, s: str) -> List[str]: start, end = 0, 10 candidate = {} while end <= len(s): seq = s[start:end] if seq in candidate: candidate[seq] +=1 else: candidate[seq] = 1 start +=1 end +=1 return [k for k,v in candidate.items() if v >=2]
Pseudo-Palindromic Paths in a Binary Tree(set이용)
Given a binary tree where node values are digits from 1 to 9. A path in the binary tree is said to be pseudo-palindromic if at least one permutation of the node values in the path is a palindrome.
Return the number of pseudo-palindromic paths going from the root node to leaf nodes.
# 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: cnt = 0 def find(self, root:TreeNode, route:List) -> bool: #마지막 노드일때 지금까지 담은 경로를 확인한다. 이때 모든 요소가 짝수가 아니면 빈 배열을 return route = route^{root.val} #★☆○☆★ 가운데 하나빼고 다 짝수여야함 또는 그냥 다 짝수 if root.left: self.find(root.left, route) if root.right: self.find(root.right, route) if not root.left and not root.right and len(route) <2 : #마지막이니 count self.cnt+=1 def pseudoPalindromicPaths (self, root: TreeNode) -> int: #find 함수돌려서 배열이 비어있지 않으면 counting self.find(root, set()) return self.cnt
'2020년 > 코테' 카테고리의 다른 글
[프로그래머스 Lv1,Lv2 다풀기 프로젝트] 소수찾기 (0) 2020.10.04 [프로그래머스 Lv1,Lv2 다풀기 프로젝트] 2016년 (0) 2020.10.03 [codility] 몸풀이용 문제 3개(BinaryGap, CyclicRotation, OddOccurrencesInArray) (0) 2020.09.28 [코테 연습] find-the-difference (0) 2020.09.24 [코테 연습] Product of Array Except Self (0) 2020.09.24