본문 바로가기

전체 글267

[Bit Operation] 비트연산 NOT 연산은 각 자릿수의 값을 반대로 바꾸는 연산이다. NOT 0111 = 1000 OR 연산은 두 값의 각 자릿수를 비교해, 둘 중 하나라도 1이 있다면 1을, 아니면 0을 계산한다. 0101 OR 0011 = 0111 XOR 연산은 두 값의 각 자릿수를 비교해, 값이 같으면 0, 다르면 1을 계산한다. 0101 XOR 0011 = 0110 AND 연산은 두 값의 각 자릿수를 비교해, 두 값 모두에 1이 있을 때에만 1을, 나머지 경우에는 0을 계산한다. 0101 AND 0011 = 0001 XOR 연산을 많이 봤는데 XOR 연산이 0으로만 된 bit를 return 한다면 같은 숫자(?)라는 것을 의미하고 아니라면 다르다는 것을 알 수 있다. [LeetCode] Find the Difference 문.. 2021. 4. 14.
[LeetCode] Find the Difference 파이썬 (Counter, A.subtract(B), bit operation, xor, reduce) from collections import Counter class Solution: def findTheDifference(self, s: str, t: str) -> str: if len(s) == 0: return t # s = "" S = Counter(s) T = Counter(t) T.subtract(S) # inplace res = [k for k, v in T.items() if v > 0] return res[0] Counter 클래스에는 subtract라는 메서드가 있다. inplace이기 때문에 이 점을 유의할 것. 다른 풀이들 class Solution(object): def findTheDifference(self, s, t): """ :type s: str :type t: str.. 2021. 4. 14.
[LeetCode] First Unique Character in a String 파이썬 (Counter, str.find) from collections import Counter class Solution: def firstUniqChar(self, s: str) -> int: idx = -1 c = Counter(s) # print(c) idx_list = [] for k,v in c.items(): # print(k,v) if v == 1: idx = s.index(k) return idx else: return idx Counter 클래스를 사용해서 풀었다. counter를 찍어보니 Counter({'e': 3, 'l': 1, 't': 1, 'c': 1, 'o': 1, 'd': 1}) 이런식으로 value 순으로 descending order로 출력은 되는데 실제 items로 iterate 해보면 입력순으로, 즉, l.. 2021. 4. 14.
[LeetCode] Ransom Note 파이썬 (dict, set, count) from collections import defaultdict class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: seen = defaultdict(int) for r in ransomNote: seen[r] += 1 for m in magazine: if m in seen: seen[m] -= 1 for v in seen.values(): if v > 0: return False return True "fihjjjjei" "hjibagacbhadfaefdjaeaebgi" defaultdict(, {'f': -1, 'i': 0, 'h': -1, 'j': 2, 'e': -2}) seen 이라는 dict에 0보다 큰.. 2021. 4. 14.
[LeetCode] Guess Number Higher or Lower 파이썬 (binary search) while 문으로 해결하려 했더니 시간초과 Binary Search로 풀어야 함. # The guess API is already defined for you. # @param num, your guess # @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 # def guess(num: int) -> int: class Solution: def guessNumber(self, n: int) -> int: left, right = 1, n while left 2021. 4. 14.
[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.