본문 바로가기

Leetcode98

[LeetCode] Add Binary 파이썬 (int, bin) 파이썬 내장 int, bin을 사용하면 10 to 2, 2 to 10이 가능 단 bin으로 했을 경우 0b100 이런식으로 str으로 return이 되기 때문에 slicing 필요 36ms class Solution: def addBinary(self, a: str, b: str) -> str: ans = int(a,base=2)+int(b,base=2) ans = bin(ans)[2:] return ans 한줄로는 그냥 이렇게 32ms 4ms 단축 return bin(int(a,2)+int(b,2))[2:] 2021. 3. 30.
[LeetCode] Plus One 파이썬 (join, list comprehension) class Solution: def plusOne(self, digits: List[int]) -> List[int]: digits = int("".join([str(x) for x in digits]))+1 digits = list(str(digits)) return digits 2021. 3. 30.
[LeetCode] Length of Last Word 파이썬 (rstrip, split) class Solution: def lengthOfLastWord(self, s): return len(s.rstrip(' ').split(' ')[-1]) 문제에 잘 설명이 안되어 있어서 그런지 downvote가 3천개 s = "a "이 경우에서 wrong answer가 발생하는 거에서 막혔는데 내가 생각했을때는 0이 맞다고 보는데 1로 return 해야된다고 하니 문제에서 last word라고 한것은 제일 오른쪽 끝에 공백이 있으면 그 바로 전 word의 length를 return 하는 것으로 요구한듯. 아무튼 여기서 가져갈 것은 strip을 사용하는 것. 2021. 3. 30.
[LeetCode] Maximum Subarray 파이썬 (dp, local max, global max) dp 사용 class Solution: def maxSubArray(self, nums: List[int]) -> int: dp = [num for num in nums] for i in range(1, len(nums)): dp[i] = max(dp[i-1]+nums[i], nums[i]) return max(dp) dp 미사용 class Solution: def maxSubArray(self, nums: List[int]) -> int: # 3/26/2021 microsoft prep max_sub = 0 global_max = float('-inf') for n in nums: max_sub = max(max_sub + n, n) global_max = max(max_sub, global_max) .. 2021. 3. 30.
[LeetCode] Search Insert Position (index) 48ms class Solution: def searchInsert(self, nums: List[int], target: int) -> int: ans = nums+[target] ans.sort() return ans.index(target) target 의 index를 for loop으로 찾기 보다는 ans에 추가하고 sort한 뒤 index로 찾기 40ms: append로 넣었을때 class Solution: def searchInsert(self, nums: List[int], target: int) -> int: nums.append(target) nums.sort() return nums.index(target) 2021. 3. 30.
[LeetCode] Implement strStr() 파이썬 (exhaustive search, find, index string) 48ms 걸리는 내 솔루션 class Solution: def strStr(self, haystack: str, needle: str) -> int: m = len(needle) if len(needle) == 0: return 0 for i in range(len(haystack)): if haystack[i] == needle[0] and haystack[i:i+m] == needle: return i else: return -1 20ms 걸리는 솔루션 class Solution: def strStr(self, haystack: str, needle: str) -> int: m, n = len(haystack), len(needle) for i in range(m - n + 1): if haystac.. 2021. 3. 29.
[LeetCode] Remove Element 파이썬 (list remove) class Solution: def removeElement(self, nums: List[int], val: int) -> int: while val in nums: nums.remove(val) 2021. 3. 29.
[LeetCode] Merge Two Sorted Lists 파이썬 (linked list) singly-linked list 에 대해 아직 이해가 부족 더 해봐야 함. # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution(object): def mergeTwoLists(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ total = [] while l1 != None: total.append(int(l1.val)) l1 = l1.next while l2 != None: total.append(int(l.. 2021. 3. 29.
[LeetCode] Valid Parentheses 파이썬 (stack, empty stack) class Solution: def isValid(self, s: str) -> bool: stack = [] for c in s: if len(stack) == 0: # 최초에 stack이 비었더라도 loop진행중 stack이 비워지면 다시 채워넣기 stack.append(c) elif stack[-1] == "{" and c == "}": stack.pop() elif stack[-1] == "[" and c == "]": stack.pop() elif stack[-1] == "(" and c == ")": stack.pop() else: stack.append(c) if len(stack) == 0: return True else: return False 방법은 맞았는데 계속 index 에러가 난 .. 2021. 3. 28.