[LeetCode] 3174. Clear Digits (Python)
·
코딩 테스트
Problem Solutionstring, stack문자열 s에서 digit이 있으면 digit 과 그 왼쪽에있는 문자를 제거하는 문제 (반복).문자열을 순회하면서 해당 index를 기준으로 digit 여부와 왼쪽 문자를 체크하여 s 를 업데이트한 후 조건에 해당되지 않을 때까지 반복한다. 다른 코드에서는 alpha이면 list에 저장하고 그 다음 문자가 digit이면 pop하여 list에서 제거한 뒤 최종적으로 string으로 concat 해서 반환한다.class Solution: def clearDigits(self, s: str) -> str: stack = [] for char in s: if char.isdigit(): ..
[LeetCode] 2364. Count Number of Bad Pairs (Python)
·
코딩 테스트
ProblemSolutionHashMapi bad pair 정의 if i bad pair의 쌍 개수 구하기관점을 바꿔서 i - nums[i] == j - nums[j] 인 good pairs를 구한 뒤 전체 - good pairs를 구한다.즉, nums[i] - i 값이 동일한 숫자끼리 good pair가 된다.그러므로, 특정 값 key = nums[i] - i를 기준으로 그룹을 만들고, 동일한 값이 등장할 때마다 good pair를 세면, 전체 쌍에서 빼서 bad pair를 구할 수 있다. 아래는 처음에 2중 for문으로 bruteforce로 풀었다가 time out 이 발생했던 코드..ㅠㅠ# solve 1)class Solution: def countBadPairs(self, nums: List..
[LeetCode] 2349. Design a Number Container System (Python)
·
코딩 테스트
Problem Solutionhash change : 해당 index에 number를 저장하거나 이미 index에 Number 가 저장되어있으면 업데이트find: number에 대해서 어떤 인덱스에 존재하는지를 찾는다. number가 저장된 index 가 많으면 가장 최솟값 반환, 없으면 -1 반환 dict를 사용해야겠다고 생각했고 value 는 list로 구현해서 sorted 로 최솟값을 구해야겠다고 생각했다.그런데 SortedSet이 있는지 몰랐는데 이걸 사용하니 따로 sorted 를 안해주어도된다! 그리고 어떤 index 에 number 가 저장되어있는지 기록하는 변수 d,각 number 에 어떤 indicies들이 저장되어있는지 기록하는 변수 map 을 사용했다. Changechange 에서 ma..
[LeetCode] 3160. Find the Number of Distinct Colors Among the Balls (Python)
·
코딩 테스트
Problem Solutionhashballs: x위치에 어떤 color 인지 저장count_colors: 특정 color 가 몇번 등장했는지 count 만약 x 위치의 공이 이미 색칠되어있다면, 해당 색상 - 1 Codeclass Solution: def queryResults(self, limit: int, queries: List[List[int]]) -> List[int]: n = len(queries) balls = dict() count_colors = defaultdict(int) answer = [] cnt = 0 for i in range(n): x, color = queries[i] ..
[LeetCode] 1726. Tuple with Same Product (Python)
·
코딩 테스트
Problem Solutionpermutation순열과 조합을 사용하여 푸는 문제.defaultdict 의 value를 리스트로 선언하여 2개의 integer 곱을 key로, tuple 을 value로 저장하였다.value 길이 (리스트)가 2 이상이면 value 길이만큼 8 x nC2 를 곱하여 경우의 수를 구하고 정답에 ++ 하였다.8을 곱하는 이유는 a*b = c*d 인 (a,b,c,d)의 경우의 수가 8이기 때문! ( 4permutation * 2 pairs)nC2를 한 이유는 value 길이 = n 에서 2개의 튜플을 선택해야되기 때문! Codefrom collections import defaultdictclass Solution: def tupleSameProduct(self, nums..
[LeetCode] 1800. Maximum Ascending Subarray Sum (Python)
·
코딩 테스트
ProblemSolutionsliding window이전 문제와 유사하게 sub array 중 오름차순이면서 총 원소합의 최대값을 구하는 문제.num array 가 100 이하라서 2중 포문을 사용해되지만 최대한 fot문을 1번만 사용하려고했다. 강력한 힌트는 The end of each ascending subarray will be the start of the nextsubarray 만들고 체크한 마지막 인덱스가 다음 순회 인덱스의 첫번째 인덱스가 된다. 아래 코드에서 idx 가 그 역할. 아래는 더 깔끔한 코드가있어서 가져와봤다.아예 처음부터 처음 0번째 값을 넣은 리스트를 선언 후 증가하는 값이 나올때마다 리스트에 추가 (cur list)작아지는 숫자가 나오면 max 값 구하고 다시 cur li..