본문 바로가기

Leetcode98

[LeetCode] Valid Perfect Square 파이썬 (Binary Search, +Lower Bound) 이렇게 풀어도 되지만 사실은 Binary Search 를 사용하는 것이 문제의 의도. class Solution: def isPerfectSquare(self, num: int) -> bool: sq = num ** 0.5 if sq == int(qs): return True return False Binary Search class Solution: def isPerfectSquare(self, num: int) -> bool: if num == 1: return True left, right = 1, num while left search right side start = mid + 1 else: end = mid # greater or equal to -> not -1 that normally do.. 2021. 4. 14.
[LeetCode] Intersection of Two Arrays II 파이썬 (defaultdict, Counter, extend) Solutions 1. Dictionary 2. Two Pointer 1. Dictionary collection 모듈에 있는 defaultdict 클래스를 사용하는 이유 (출처: link) 아래 처럼 dict를 만들때 not in 일 경우 0으로 초기 설정을 해주는 코드가 들어가야 한다. 하지만 defaultdict 클래스를 사용하게 되면 초기화 설정을 하는 부분을 입력하지 않아도 된다. def countLetters(word): counter = {} for letter in word: if letter not in counter: counter[letter] = 0 counter[letter] += 1 return counter from collections import defaultdict def.. 2021. 4. 13.
[LeetCode] Intersection of Two Arrays 파이썬 (set, intersection) set 자료형의 intersection 사용 class Solution: def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: return list(set(nums1).intersection(nums2)) difference 도 차집합 구할 떄 사용 가능 list(set(nums1).difference(nums2)) 2021. 4. 13.
[LeetCode] Reverse Vowels of String 파이썬 (swap, two pointer) reverse string 문제에서 진화된 문제 i, j = 0, len(s) - 1 while i < j: s[i], s[j] = s[j], s[i] i += 1 j -= 1 2개의 변수(i,j)들을 활용해서 swap dict나 list 뿐만 아니라 string 도 not in 구문이 가능하다는 점. i는 forward j는 backward 탐색 ㄱ vowel의 위치를 찾을 경우 i,j swap class Solution(object): def reverseVowels(self, s): """ :type s: str :rtype: str """ vowels = "aeiou" string = list(s) i, j = 0, len(s) - 1 while i < j: if string[i].lower() .. 2021. 4. 13.
[LeetCode] Reverse String 파이썬 (in-place, list.reverse()) class Solution: def reverseString(self, s: List[str]) -> None: """ Do not return anything, modify s in-place instead. """ i, j = 0, len(s) - 1 while i < j: s[i], s[j] = s[j], s[i] i += 1 j -= 1 왼쪽 끝부터, 오른쪽 끝부터 탐색하면서 서로 swap string의 길이가 짝, 홀 상관없이 i None: """ Do not return anything, modify s in-place instead. """ s.reverse() 2021. 4. 12.
[LeetCode] Word Pattern 파이썬 (isomorphic, contract mapping) class Solution: def wordPattern(self, pattern: str, s: str) -> bool: s = list(s.split(" ")) if len(pattern) != len(s): return False s2t, t2s = {}, {} for p, w in zip(pattern, s): if w not in s2t and p not in t2s: s2t[w] = p t2s[p] = w elif w not in s2t or s2t[w] != p: # Contradict mapping. return False return True 이 문제를 본 순간 [LeetCode] Isomorphic Strings 문제가 떠올랐다. ygseo.tistory.com/221 len으로 먼저 .. 2021. 4. 12.
[LeetCode] Move Zeros 파이썬 (in-place) in-place modifiy class Solution(object): def moveZeroes(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ pos = 0 for i in range(len(nums)): if nums[i]: nums[i], nums[pos] = nums[pos], nums[i] pos += 1 nums[i]가 0이 아닌경우 0의 위치와 swap한다. # i track non zero location # pos track zero location # print(nums[i], nums[pos] , "i={}, pos={}".format.. 2021. 4. 12.
[LeetCode] Missing Number 파이썬 class Solution: def missingNumber(self, nums: List[int]) -> int: nums = sorted(nums) for idx, value in enumerate(nums): if idx != nums[idx]: return idx else: return len(nums) enumerate 써서 idx로 확인 [0,1] 같은 경우 n은 2이지만 for문 안에서는 None으로 return 되기 때문에 이와 같은 경우는 for-else문을 써서 for문이 오류없이 종료된다면 [0,1] 같은 경우이기 때문에 return len(nums)를 해준다. 2021. 4. 12.
[LeetCode] Ugly Number 파이썬 class Solution: # @param {integer} num # @return {boolean} def isUgly(self, num): if num == 0: return False for i in [2, 3, 5]: while num % i == 0: num /= i return num == 1 2021. 4. 11.