본문 바로가기

분류 전체보기267

[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] Remove Duplicates from Sorted Array 파이썬 (list[:] shallow copy) class Solution: def removeDuplicates(self, nums: List[int]) -> int: nums[:] = list(set(nums)) nums.sort() return len(nums) stackoverflow.com/questions/4081561/what-is-the-difference-between-list-and-list-in-python list[:] -> shallow-copies the list 비추가 6695에 달하는 문제 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.
[LeetCode] Longest Common Prefix 파이썬 (zip, list comprehension, set) class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: strs = [list(x) for x in strs] strs = zip(*strs) pre = "" for a in strs: if len(set(a)) == 1: pre += a[0] else: break return pre # output # [['f', 'l', 'o', 'w', 'e', 'r'], ['f', 'l', 'o', 'w'], ['f', 'l', 'i', 'g', 'h', 't']] # ('f', 'f', 'f') # a output # {'f'} # set(a) # 1 # len(set(a)) # ('l', 'l', 'l') # {'l'} # 1 # ('o'.. 2021. 3. 28.
[LeetCode] Roman to Integer 파이썬 (dict, stack, deque) from collections import deque class Solution: def romanToInt(self, s: str) -> int: symbol = {"IV":4, "IX":9, "XL":40, "XC":90, "CD":400, "CM":900} roman = {"I":1,"V":5,"X":10,"L":50,"C":100,"D":500, "M":1000, "IV":4, "IX":9, "XL":40, "XC":90, "CD":400, "CM":900} stack = deque() stack.append((s[0],0)) for i in range(1, len(s)): pattern = stack[-1][0]+s[i] if pattern in symbol: stack.pop() stack.a.. 2021. 3. 26.
[LeetCode] Palindrom Number 파이썬 (reverse str) class Solution: def isPalindrome(self, x: int) -> bool: if str(x) == str(x)[::-1]: return True else: return False Revese Integer에 있던 str reverse 활용함 메모리에서는 50%인데 시간 상위 솔루션은 class Solution: def isPalindrome(self, x: int) -> bool: if x bool: x = str(x) if x == x[::-1]: return True return False str전환을 한번만해서 빠르게 계산되도록 메모리 측면에서의 상위 솔루션 class Solution: def isPalindrome(self, x: int) -> bool: if x < 0:.. 2021. 3. 25.