diff --git a/10. Regular Expression Matching.py b/10. Regular Expression Matching.py new file mode 100644 index 0000000..d69acf1 --- /dev/null +++ b/10. Regular Expression Matching.py @@ -0,0 +1,102 @@ +# Recursion, Slow, but accepted :) +class Solution(object): + def isMatch(self, s, p, p_pre=None): + """ + :type s: str + :type p: str + :rtype: bool + """ + print ("s='%s',p='%s',p_pre='%s'" % (str(s),str(p),str(p_pre))) + if len(s)==0: + if len(p)==0: + return True + elif len(p)>=1 and p[0] == '*': + return self.isMatch(s[:],p[1:],p_pre=p_pre) + elif len(p)>=2 and p[1] == '*': + return self.isMatch(s[:],p[2:],p_pre=p_pre) + else: + return False + else: + if len(p)==0: + return False + else: + pass + # + result = False + # + if (s[0] == p[0] or p[0] =='.'): + result = self.isMatch(s[1:],p[1:],p_pre=p[0]) + if result == True: + return True + # print '1' + # + if (s[0] == p_pre or p_pre =='.') and p[0] == '*': + result = self.isMatch(s[1:],p[:],p_pre=p_pre) + if result == True: + return True + # print '2' + # + if len(p)>=2 and p[1] == '*': + result = self.isMatch(s[:],p[2:],p_pre=p_pre) + if result == True: + return True + # print '3' + # + if p[0] == '*': + result = self.isMatch(s[:],p[1:],p_pre=p_pre) + if result == True: + return True + return result + + +# Recursion standard anwser, also quite slow, but faster and cleaner than above solution +class Solution(object): + def isMatch(self, text, pattern): + if not pattern: + return not text + + first_match = bool(text) and pattern[0] in {text[0], '.'} + + if len(pattern) >= 2 and pattern[1] == '*': + return (self.isMatch(text, pattern[2:]) or + first_match and self.isMatch(text[1:], pattern)) + else: + return first_match and self.isMatch(text[1:], pattern[1:]) + + +# dynamic programming solution +class Solution(object): + def isMatch(self, text, pattern): + memo = {} + def dp(i, j): + if (i, j) not in memo: + if j == len(pattern): + ans = i == len(text) + else: + first_match = i < len(text) and pattern[j] in {text[i], '.'} + if j+1 < len(pattern) and pattern[j+1] == '*': + ans = dp(i, j+2) or first_match and dp(i+1, j) + else: + ans = first_match and dp(i+1, j+1) + + memo[i, j] = ans + return memo[i, j] + + return dp(0, 0) + + + +a = Solution() + + + +a.isMatch('asd','asd') +a.isMatch('aasd','a*sd') +a.isMatch('aasd','.*sd') +a.isMatch('aasd','.*') +a.isMatch('sd','*sd') +a.isMatch('','*') +a.isMatch('','c*c*') +a.isMatch('abbabaaaaaaacaa',"a*.*b.a.*c*b*a*c*") +a.isMatch('','*c*b*a*c*') +s='',p='*c*b*a*c*',p_pre='.' \ No newline at end of file diff --git a/11. Container With Most Water.py b/11. Container With Most Water.py new file mode 100644 index 0000000..7069ce6 --- /dev/null +++ b/11. Container With Most Water.py @@ -0,0 +1,107 @@ +# O(n), accepted, (Two Pointer Approach, code simplified) +class Solution(object): + def maxArea(self, height): + """ + :type height: List[int] + :rtype: int + """ + max_vol = 0 + length = len(height) + left_index = 0 + right_index = length - 1 + while left_index <= right_index: + max_vol = max(max_vol,(min(height[left_index],height[right_index])*(right_index-left_index))) + if height[left_index] >= height[right_index]: + right_index = right_index - 1 + else: + left_index = left_index + 1 + return max_vol + +# O(n), accepted, (Two Pointer Approach) +class Solution(object): + def maxArea(self, height): + """ + :type height: List[int] + :rtype: int + """ + max_vol = 0 + length = len(height) + left_index = 0 + right_index = length - 1 + left = height[left_index] + right = height[right_index] + while left_index <= right_index: + max_vol = max(max_vol,(min(left,right)*(right_index-left_index))) + if left >= right: + right_index = right_index - 1 + right = height[right_index] + else: + left_index = left_index + 1 + left = height[left_index] + return max_vol + + +# O(n^2) with max_left & max_right optimisation, still too slow +class Solution(object): + def maxArea(self, height): + """ + :type height: List[int] + :rtype: int + """ + max_vol = 0 + max_left = 0 + length = len(height) + for i in range(0,length-1): + if height[i] > max_left: + max_left = height[i] + max_right = 0 + for j in reversed(range(i,length)): + if height[j] > max_right: + max_right = height[j] + temp_vol = min(height[i],height[j])*(j-i) + max_vol = max(max_vol,temp_vol) + return max_vol + + +# O(n^2) with max_left optimisation, still too slow +class Solution(object): + def maxArea(self, height): + """ + :type height: List[int] + :rtype: int + """ + max_vol = 0 + max_left = 0 + length = len(height) + for i in range(0,length-1): + if height[i] > max_left: + max_left = height[i] + for j in range(i,length): + temp_vol = min(height[i],height[j])*(j-i) + max_vol = max(max_vol,temp_vol) + return max_vol + + +# O(n^2), too slow +class Solution(object): + def maxArea(self, height): + """ + :type height: List[int] + :rtype: int + """ + max_vol = 0 + length = len(height) + for i in range(0,length-1): + for j in range(i,length): + temp_vol = min(height[i],height[j])*(j-i) + max_vol = max(max_vol,temp_vol) + return max_vol + + + + + + + + + diff --git a/1108. Defanging an IP Address.py b/1108. Defanging an IP Address.py new file mode 100644 index 0000000..04ec4fa --- /dev/null +++ b/1108. Defanging an IP Address.py @@ -0,0 +1,8 @@ +class Solution(object): + def defangIPaddr(self, address): + """ + :type address: str + :rtype: str + """ + address = address.replace('.','[.]') + return address \ No newline at end of file diff --git a/1109. Corporate Flight Bookings.py b/1109. Corporate Flight Bookings.py new file mode 100644 index 0000000..4099218 --- /dev/null +++ b/1109. Corporate Flight Bookings.py @@ -0,0 +1,97 @@ +## O(n) +class Solution: + def corpFlightBookings(self, bookings, n): + res = [0] * (n + 1) + for start, end, seats in bookings: + res[start-1] += seats + res[end] -= seats + s = 0 + for index, i in enumerate(res): + res[index] += s + s += i + return res[:-1] + +## Too Slow (Brute Force) +class Solution(object): + def corpFlightBookings(self, bookings, n): + """ + :type bookings: List[List[int]] + :type n: int + :rtype: List[int] + """ + # booking_final = [[0]*n for i in range(len(bookings))] + booking_final2 = [0]*n + for start,end,seat in bookings: + for flight in range(start-1,end): + booking_final2[flight]=booking_final2[flight]+seat + return booking_final2 + +## Too Slow +from operator import add +class Solution(object): + def corpFlightBookings(self, bookings, n): + """ + :type bookings: List[List[int]] + :type n: int + :rtype: List[int] + """ + # booking_final = [[0]*n for i in range(len(bookings))] + booking_final2 = [0]*n + for i in range(len(bookings)): + booking = bookings[i] + temp=[0]*(booking[0]-1)+[booking[2]]*(booking[1]-booking[0]+1)+[0]*(n-booking[1]) + booking_final2 = list( map(add, booking_final2, temp )) + return booking_final2 + + + +## Too Slow +from operator import add +class Solution(object): + def corpFlightBookings(self, bookings, n): + """ + :type bookings: List[List[int]] + :type n: int + :rtype: List[int] + """ + # booking_final = [[0]*n for i in range(len(bookings))] + booking_final2 = [0]*n + for i in range(len(bookings)): + booking = bookings[i] + temp=[0]*(booking[0]-1)+[booking[2]]*(booking[1]-booking[0]+1)+[0]*(n-booking[1]) + booking_final2 = list( map(add, booking_final2, temp )) + return booking_final2 + + + +## Memory Exceeded +from operator import add +class Solution(object): + def corpFlightBookings(self, bookings, n): + """ + :type bookings: List[List[int]] + :type n: int + :rtype: List[int] + """ + booking_final = [[0]*n for i in range(len(bookings))] + booking_final2 = [0]*n + for i in range(len(bookings)): + booking = bookings[i] + booking_final[i]=[0]*(booking[0]-1)+[booking[2]]*(booking[1]-booking[0]+1)+[0]*(n-booking[1]) + for i in range(len(bookings)): + booking_final2 = list( map(add, booking_final2, booking_final[i] )) + return booking_final2 + +## Too Slow +class Solution(object): + def corpFlightBookings(self, bookings, n): + """ + :type bookings: List[List[int]] + :type n: int + :rtype: List[int] + """ + booking_final = [0]*n + for booking in bookings: + for flight in range(booking[0],booking[1]+1): + booking_final[flight-1]=booking_final[flight-1]+booking[2] + return booking_final \ No newline at end of file diff --git a/12. Integer to Roman.py b/12. Integer to Roman.py new file mode 100644 index 0000000..e62b645 --- /dev/null +++ b/12. Integer to Roman.py @@ -0,0 +1,39 @@ +Symbol Value +I 1 +V 5 +X 10 +L 50 +C 100 +D 500 +M 1000 + +I can be placed before V (5) and X (10) to make 4 and 9. +X can be placed before L (50) and C (100) to make 40 and 90. +C can be placed before D (500) and M (1000) to make 400 and 900. + +class Solution(object): + def intToRoman(self, num): + """ + :type num: int + :rtype: str + """ + translate_dict = { 'M' : 1000, + 'CM': 900, + 'D' : 500, + 'CD': 400, + 'C' : 100, + 'XC': 90, + 'L' : 50, + 'XL': 40, + 'X' : 10, + 'IX': 9, + 'V' : 5, + 'IV': 4, + 'I' : 1 + } + result='' + for l in ['M','CM','D','CD','C','XC','L','XL','X','IX','V','IV','I']: + while num >= translate_dict[l]: + result = result + l + num = num - translate_dict[l] + return result \ No newline at end of file diff --git a/13. Roman to Integer.py b/13. Roman to Integer.py new file mode 100644 index 0000000..333b9bc --- /dev/null +++ b/13. Roman to Integer.py @@ -0,0 +1,39 @@ +Symbol Value +I 1 +V 5 +X 10 +L 50 +C 100 +D 500 +M 1000 + +I can be placed before V (5) and X (10) to make 4 and 9. +X can be placed before L (50) and C (100) to make 40 and 90. +C can be placed before D (500) and M (1000) to make 400 and 900. + +class Solution(object): + def romanToInt(self, s): + """ + :type s: str + :rtype: int + """ + translate_dict = { 'M' : 1000, + 'CM': 900, + 'D' : 500, + 'CD': 400, + 'C' : 100, + 'XC': 90, + 'L' : 50, + 'XL': 40, + 'X' : 10, + 'IX': 9, + 'V' : 5, + 'IV': 4, + 'I' : 1 + } + result = 0 + for l in ['M','CM','D','CD','C','XC','L','XL','X','IX','V','IV','I']: + while s.find(l) == 0: + result = result + translate_dict[l] + s = s[len(l):] + return result \ No newline at end of file diff --git a/14. Longest Common Prefix.py b/14. Longest Common Prefix.py new file mode 100644 index 0000000..cf23f5b --- /dev/null +++ b/14. Longest Common Prefix.py @@ -0,0 +1,25 @@ +class Solution(object): + def longestCommonPrefix(self, strs): + """ + :type strs: List[str] + :rtype: str + """ + + result = '' + n = len(strs) + if n == 0: + return '' + i = 0 + flag = True + while flag: + if i < len(strs[0]): + s = strs[0][i] + for j in range(1,n): + if i >= len(strs[j]) or s != strs[j][i]: + flag = False + if flag: + result = result + s + i = i + 1 + else: + flag = False + return result \ No newline at end of file diff --git a/15. 3Sum.py b/15. 3Sum.py new file mode 100644 index 0000000..f6cc5c2 --- /dev/null +++ b/15. 3Sum.py @@ -0,0 +1,94 @@ +# O(n^2) +class Solution(object): + def threeSum(self, nums): + res = [] + nums.sort() + for i in xrange(len(nums)-2): + if i > 0 and nums[i] == nums[i-1]: + continue + l, r = i+1, len(nums)-1 + while l < r: + s = nums[i] + nums[l] + nums[r] + if s < 0: + l +=1 + elif s > 0: + r -= 1 + else: + res.append((nums[i], nums[l], nums[r])) + while l < r and nums[l] == nums[l+1]: + l += 1 + while l < r and nums[r] == nums[r-1]: + r -= 1 + l += 1; r -= 1 + return res + + +# Too slow.. construction of set is O(n), so overall O(n^3) +class Solution(object): + def threeSum(self, nums): + """ + :type nums: List[int] + :rtype: List[List[int]] + """ + result = [] + dp = set() + nums.sort() + for i in range(len(nums) - 2): + if i > 0 and nums[i] == nums[i-1]: + continue + if 0-nums[i]-nums[i+1] < nums[i]: + break + for j in range(i+1,len(nums)): + if (nums[i],nums[j]) in dp: + continue + temp = set(nums[j+1:len(nums)]) + target = 0-nums[i]-nums[j] + if target in temp: + dp.add((nums[i],nums[j])) + dp.add((target,nums[j])) + dp.add((nums[i],target)) + ans = [nums[i],target,nums[j]] + result.append(ans) + # continue + return result + +# O(n^2) +class Solution(object): + def threeSum(self, nums): + """ + :type nums: List[int] + :rtype: List[List[int]] + """ + result = [] + # dp = set() + nums.sort() + for i in range(len(nums) - 2): + if i > 0 and nums[i] == nums[i-1]: + continue + if 0-nums[i]-nums[i+1] < nums[i]: + break + j=i+1 + k=len(nums)-1 + while j=k: + # break + if nums[i]+nums[j]+nums[k] < 0 + j=j+1 + elif nums[i]+nums[j]+nums[k] == 0: + # dp.add((nums[i],nums[j])) + ans = [nums[i],nums[j],nums[k]] + result.append(ans) + while j= 3: + result = nums[0]+nums[1]+nums[2] + else: + return sum(a) + nums.sort() + for i in range(len(nums) - 2): + if i > 0 and nums[i] == nums[i-1]: + continue + j=i+1 + k=len(nums)-1 + while jtarget: + break + while j < length-2: + k = j+1 + l = length-1 + if nums[i]+nums[j]+2*nums[k]>target: + break + while ktarget or nums[i]+nums[j]+2*nums[l] l and nums[r] == nums[r + 1]: + r -= 1 + elif nums[l] + nums[r] < target: + l += 1 + else: + r -= 1 + else: + for i in range(0, len(nums)-N+1): # careful about range + if target < nums[i]*N or target > nums[-1]*N: # take advantages of sorted list + break + if i == 0 or i > 0 and nums[i-1] != nums[i]: # recursively reduce N + self.findNsum(nums[i+1:], target-nums[i], N-1, result+[nums[i]], results) + return + + + +a=Solution() +a.fourSum([-7,-5,0,7,1,1,-10,-2,7,7,-2,-6,0,-10,-5,7,-8,5],28) diff --git a/19. Remove Nth Node From End of List.py b/19. Remove Nth Node From End of List.py new file mode 100644 index 0000000..4650aca --- /dev/null +++ b/19. Remove Nth Node From End of List.py @@ -0,0 +1,74 @@ +19. Remove Nth Node From End of List (Medium) + +Given a linked list, remove the n-th node from the end of list and return its head. + +Example: + +Given linked list: 1->2->3->4->5, and n = 2. + +After removing the second node from the end, the linked list becomes 1->2->3->5. +Note: + +Given n will always be valid. + +Follow up: + +Could you do this in one pass? + +# Definition for singly-linked list. +# class ListNode(object): +# def __init__(self, x): +# self.val = x +# self.next = None + +# one pass +class Solution(object): + count = 0 + removed = False + def removeNthFromEnd(self, head, n): + """ + :type head: ListNode + :type n: int + :rtype: ListNode + """ + self.removeNthFromEnd_v2(head, n) + if not self.removed: + head=head.next + + return head + + def removeNthFromEnd_v2(self, head, n): + if head.next: + self.removeNthFromEnd_v2(head.next, n) + self.count = self.count + 1 + if self.count == n+1: + head.next = head.next.next + self.removed = True + return head + + +# 2 pass, faster +class Solution(object): + count = 0 + removed = False + def removeNthFromEnd(self, head, n): + """ + :type head: ListNode + :type n: int + :rtype: ListNode + """ + count = 0 + head_temp=head + while head_temp is not None: + count = count + 1 + head_temp=head_temp.next + if count == n: + return head.next + i=1 + head_temp=head + while i < count-n: + i=i+1 + head_temp=head_temp.next + head_temp.next = head_temp.next.next + return head + diff --git a/20. Valid Parentheses.py b/20. Valid Parentheses.py new file mode 100644 index 0000000..dc6efe7 --- /dev/null +++ b/20. Valid Parentheses.py @@ -0,0 +1,42 @@ +# accepted +class Solution(object): + def isValid(self, s): + """ + :type s: str + :rtype: bool + """ + stack = [] + mapping = {'{':'}','(':')','[':']'} + for i in s: + if i in ('{','[','('): + stack.append(i) + elif not stack or mapping[stack.pop()] != i: + return False + if len(stack) == 0: + return True + else: + return False + + +# slightly faster +class Solution(object): + def isValid(self, s): + """ + :type s: str + :rtype: bool + """ + mapping = {'{':'}','(':')','[':']'} + i = 0 + while i < len(s): + if s[i] in ('{','[','('): + i=i+1 + else: + if i>=1 and mapping[s[i-1]] == s[i]: + s = s[:i-1]+s[i+1:] + i = i-1 + else: + return False + if s == '': + return True + else: + return False diff --git a/21. Merge Two Sorted Lists.py b/21. Merge Two Sorted Lists.py new file mode 100644 index 0000000..5958ece --- /dev/null +++ b/21. Merge Two Sorted Lists.py @@ -0,0 +1,43 @@ +# Definition for singly-linked list. +# class ListNode(object): +# def __init__(self, x): +# self.val = x +# self.next = None + +class Solution(object): + def mergeTwoLists(self, l1, l2): + """ + :type l1: ListNode + :type l2: ListNode + :rtype: ListNode + """ + if l1 is None or l2 is None: + return l1 or l2 + if l1.val <= l2.val: + head = l1 + l1 = l1.next + else: + head = l2 + l2 = l2.next + current = head + while l1 is not None and l2 is not None: + if l1.val <= l2.val: + current.next = l1 + current = l1 + l1=l1.next + else: + current.next = l2 + current = l2 + l2=l2.next + if l1 is not None: + current.next = l1 + if l2 is not None: + current.next = l2 + return head + + + + + + + diff --git a/22. Generate Parentheses.py b/22. Generate Parentheses.py new file mode 100644 index 0000000..bca672c --- /dev/null +++ b/22. Generate Parentheses.py @@ -0,0 +1,26 @@ +class Solution(object): + dp = {1:['()'],2:['()()','(())']} + def generateParenthesis(self, n): + """ + :type n: int + :rtype: List[str] + """ + self.sub_gen(n) + return list(set(self.dp[n])) + # + def sub_gen(self, n): + if n in self.dp: + return self.dp[n] + if n not in self.dp: + temp_list = [] + for i in range(1,n): + for item1 in self.sub_gen(i): + for item2 in self.sub_gen(n-i): + temp_list.append(item1+item2) + for item in self.sub_gen(n-1): + temp_list.append('('+item+')') + self.dp.update({n:temp_list}) + return self.dp[n] + +a = Solution() +a.generateParenthesis(3) diff --git a/23. Merge k Sorted Lists.py b/23. Merge k Sorted Lists.py new file mode 100644 index 0000000..b3c1859 --- /dev/null +++ b/23. Merge k Sorted Lists.py @@ -0,0 +1,85 @@ +# Definition for singly-linked list. +# class ListNode(object): +# def __init__(self, x): +# self.val = x +# self.next = None + +# Very slow, but accepted, Approach 2: Compare one by one +class Solution(object): + def mergeKLists(self, lists): + """ + :type lists: List[ListNode] + :rtype: ListNode + """ + i=0 + while i < len(lists): + if lists[i] is None or lists[i] == []: + lists.remove(lists[i]) + else: + i=i+1 + if len(lists)<=0: + return None + self.find_min(lists) + head = lists[0] + current = head + lists[0] = lists[0].next + if lists[0] is None: + lists.remove(lists[0]) + if len(lists)<=0: + return head + while len(lists)>1: + self.find_min(lists) + current.next=lists[0] + current = current.next + lists[0] = lists[0].next + if lists[0] is None: + lists.remove(lists[0]) + current.next=lists[0] + return head + # + def find_min(self,lists): + temp_min = lists[0].val + for i in range(1,len(lists)): + if lists[i].val < temp_min: + temp_min = lists[i].val + temp = lists[i] + lists[i] = lists[0] + lists[0] = temp + return 0 + + +class ListNode(object): + def __init__(self, x): + self.val = x + self.next = None + +a0 = ListNode(1) +a1 = ListNode(3) +a2 = ListNode(6) +a0.next=a1 +a1.next=a2 + +b0 = ListNode(2) +b1 = ListNode(4) +b2 = ListNode(5) +b0.next=b1 +b1.next=b2 + +c0 = ListNode(0) +c1 = ListNode(3.5) +c2 = ListNode(10) +c0.next=c1 +c1.next=c2 + +l=[b0,a0,c0] + +sol = Solution() +anw = sol.mergeKLists(l) +print_node(anw) + +def print_node(node_a): + while node_a is not None: + print (node_a.val) + node_a = node_a.next + + diff --git a/24. Swap Nodes in Pairs.py b/24. Swap Nodes in Pairs.py new file mode 100644 index 0000000..3c25b49 --- /dev/null +++ b/24. Swap Nodes in Pairs.py @@ -0,0 +1,48 @@ +# Definition for singly-linked list. +# class ListNode(object): +# def __init__(self, x): +# self.val = x +# self.next = None + +class Solution(object): + def swapPairs(self, head): + """ + :type head: ListNode + :rtype: ListNode + """ + i = 0 + pre_first = ListNode(0) + pre_first.next = head + pre_head = pre_first + first = None + second = None + pos_second = None + current = head + while current is not None: + if i % 2 == 0: + first = current + current = current.next + else: + second = current + current = current.next + pos_second = second.next + pre_first.next = second + second.next = first + first.next = pos_second + pre_first = first + i = i + 1 + return pre_head.next + + + + + + + + + + + + + + diff --git a/25. Reverse Nodes in k-Group.py b/25. Reverse Nodes in k-Group.py new file mode 100644 index 0000000..40ffb76 --- /dev/null +++ b/25. Reverse Nodes in k-Group.py @@ -0,0 +1,52 @@ +# Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. + +# k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is. + +# Example: + +# Given this linked list: 1->2->3->4->5 + +# For k = 2, you should return: 2->1->4->3->5 + +# For k = 3, you should return: 3->2->1->4->5 + +# Note: + +# Only constant extra memory is allowed. +# You may not alter the values in the list's nodes, only nodes itself may be changed. + + + +# Definition for singly-linked list. +# class ListNode(object): +# def __init__(self, x): +# self.val = x +# self.next = None + +class Solution(object): + def reverseKGroup(self, head, k): + """ + :type head: ListNode + :type k: int + :rtype: ListNode + """ + i = 0 + pre_first = ListNode(0) + pre_first.next = head + pre_head = pre_first + current = head + # + temp = [ListNode(None)]*k + # + while current is not None: + temp[i % k] = current + current = current.next + if i % k == k-1: + pre_first.next = temp[k-1] + for temp_i in reversed(range(1,k)): + temp[temp_i].next = temp[temp_i-1] + temp[0].next = current + pre_first = temp[0] + i = i + 1 + return pre_head.next + diff --git a/26. Remove Duplicates from Sorted Array.py b/26. Remove Duplicates from Sorted Array.py new file mode 100644 index 0000000..f05a480 --- /dev/null +++ b/26. Remove Duplicates from Sorted Array.py @@ -0,0 +1,117 @@ +# Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length. + +# Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. + +# Example 1: + +# Given nums = [1,1,2], + +# Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. + +# It doesn't matter what you leave beyond the returned length. +# Example 2: + +# Given nums = [0,0,1,1,1,2,2,3,3,4], + +# Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively. + +# It doesn't matter what values are set beyond the returned length. +# Clarification: + +# Confused why the returned value is an integer but your answer is an array? + +# Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well. + +# Internally you can think of this: + +# // nums is passed in by reference. (i.e., without making a copy) +# int len = removeDuplicates(nums); + +# // any modification to nums in your function would be known by the caller. +# // using the length returned by your function, it prints the first len elements. +# for (int i = 0; i < len; i++) { +# print(nums[i]); +# } + + +# too slow +class Solution(object): + def removeDuplicates(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + i = 0 + count = 1 + max_length = len(nums) + while i < max_length-1: + # print i + # print nums + # print max_length + # print + j=i+1 + d=0 + while j <= max_length-1 and nums[i] == nums[j]: + j=j+1 + d=d+1 + if j <= max_length-1: + count = count + 1 + if j>i+1: + k=i+1 + while j < max_length: + nums[k] = nums[j] + j=j+1 + k=k+1 + max_length = max_length - d + i=i+1 + # print nums + return count + +# Accepted +class Solution(object): + def removeDuplicates(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + if len(nums) == 0: + return 0 + i = 0 + count = 1 + max_length = len(nums) + while i < max_length-1: + while i < max_length-1 and nums[i] == nums[i+1]: + i=i+1 + if i < max_length-1: + nums[count] = nums[i+1] + count = count + 1 + i=i+1 + return count + +a=Solution() +a.removeDuplicates([0,0]) +a.removeDuplicates([0,0,1,1,1,2,2,3,3,4]) + +# Solution provide by Leetcode, slightly faster +class Solution(object): + def removeDuplicates(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + if len(nums) == 0: + return 0 + i = 0 + j = 1 + max_length = len(nums) + while j < max_length: + if nums[i] != nums[j]: + i=i+1 + nums[i]=nums[j] + j=j+1 + return i+1 + +a=Solution() +a.removeDuplicates([0,0]) +a.removeDuplicates([0,0,1,1,1,2,2,3,3,4]) + diff --git a/3. Longest Substring Without Repeating Characters.py b/3. Longest Substring Without Repeating Characters.py new file mode 100644 index 0000000..837256e --- /dev/null +++ b/3. Longest Substring Without Repeating Characters.py @@ -0,0 +1,125 @@ +# too slow +class Solution(object): + def lengthOfLongestSubstring(self, s): + """ + :type s: str + :rtype: int + """ + max_length = 0 + for i in range(0,len(s)): + temp="" + for j in range(i,len(s)): + if s[j] not in temp: + temp = temp+s[j] + else: + break + max_length=max(max_length,len(temp)) + return min(max_length,len(s)) + +# too slow V2 +class Solution(object): + def lengthOfLongestSubstring(self, s): + """ + :type s: str + :rtype: int + """ + max_length = 0 + temp_max_length = 0 + for i in range(0,len(s)): + for j in range(i,len(s)): + index={} + temp="" + temp_max_length = 0 + for k in range(i,j+1): + try: + index[s[k]] + k=j+1 + break + except: + index[s[k]]=1 + temp_max_length = temp_max_length + 1 + max_length=max(max_length,temp_max_length) + return min(max_length,len(s)) + + +# too slow V2 +class Solution(object): + def lengthOfLongestSubstring(self, s): + """ + :type s: str + :rtype: int + """ + max_length = 0 + for i in range(0,len(s)): + index=[] + for j in range(i,len(s)): + if s[j] in index: + break + else: + index.append(s[j]) + max_length=max(max_length,len(index)) + return min(max_length,len(s)) + +# too slow V3 +class Solution(object): + def lengthOfLongestSubstring(self, s): + """ + :type s: str + :rtype: int + """ + max_length = 0 + for i in range(0,len(s)-1): + index=set() + for j in range(i,len(s)): + if s[j] in index: + break + else: + index.add(s[j]) + max_length=max(max_length,len(index)) + return min(max_length,len(s)) + + +# Approach 2: Sliding Window +class Solution(object): + def lengthOfLongestSubstring(self, s): + """ + :type s: str + :rtype: int + """ + max_length = 0 + len_s = len(s) + i=0 + j=0 + set0=set() + while i <= len_s-1 and j <= len_s-1: + if s[j] in set0: + set0.remove(s[i]) + i=i+1 + else: + set0.add(s[j]) + j=j+1 + max_length=max(max_length,len(set0)) + return max_length + +# Approach 3: Sliding Window Optimised +class Solution: + def lengthOfLongestSubstring(self, s): + dicts = {} + maxlength = i = 0 + for j,value in enumerate(s): + if value in dicts: + j2 = dicts[value] + 1 + if j2 > i: + i = j2 + curr_length = j - i + 1 + if curr_length > maxlength: + maxlength = curr_length + dicts[value] = j + return maxlength + + + +a=Solution() +a.lengthOfLongestSubstring('abcdedf') + + diff --git a/4. Median of Two Sorted Arrays.py b/4. Median of Two Sorted Arrays.py new file mode 100644 index 0000000..3acd0b4 --- /dev/null +++ b/4. Median of Two Sorted Arrays.py @@ -0,0 +1,218 @@ +# Passed +import bisect +class Solution(object): + def findMedianSortedArrays(self, nums1, nums2): + """ + :type nums1: List[int] + :type nums2: List[int] + :rtype: float + """ + print nums1, nums2 + print len(nums1),len(nums2) + smaller_len = min(len(nums1),len(nums2)) + if len(nums1)+len(nums2) == 1: + return sum(nums1)+sum(nums2) + # + if len(nums1) == 0: + print 'in 1' + return self.find_median(nums2) + # + if len(nums2) == 0: + print 'in 2' + return self.find_median(nums1) + # + if len(nums1) == 1: + print 'in 3' + bisect.insort(nums2, nums1[0]) + return self.find_median(nums2) + # + if len(nums2) == 1: + print 'in 4' + bisect.insort(nums1, nums2[0]) + return self.find_median(nums1) + # + if len(nums1) == 2: + print 'in 5' + bisect.insort(nums2, nums1[0]) + bisect.insort(nums2, nums1[1]) + return self.find_median(nums2) + # + if len(nums2) == 2: + print 'in 6' + bisect.insort(nums1, nums2[0]) + bisect.insort(nums1, nums2[1]) + return self.find_median(nums1) + if nums1[-1] <= nums2[0]: + print 'in 7' + return self.find_median(nums1 + nums2) + # + if nums2[-1] <= nums1[0]: + print 'in 8' + return self.find_median(nums2 + nums1) + # + median1 = self.find_median(nums1) + median2 = self.find_median(nums2) + if median1 < median2: + print 'in 9' + return self.findMedianSortedArrays(nums1[(smaller_len-1)//2:], nums2[:(len(nums2)) - (smaller_len-1)//2]) + elif median1 == median2: + print 'in 10' + return median1 + else: + print 'in 11' + return self.findMedianSortedArrays(nums2[(smaller_len-1)//2:], nums1[:(len(nums1)) - (smaller_len-1)//2]) + # + def find_median(self,a): + if len(a) % 2 ==0: + return (a[len(a)//2]+a[len(a)//2-1]) / 2.0 + else: + return a[len(a)//2] + +# Optimised +import bisect +class Solution(object): + def findMedianSortedArrays(self, nums1, nums2): + """ + :type nums1: List[int] + :type nums2: List[int] + :rtype: float + """ + if len(nums1) > 2 and len(nums2) > 2: + print nums1, nums2 + print len(nums1),len(nums2) + smaller_len = min(len(nums1),len(nums2)) + # if len(nums1)+len(nums2) == 1: + # return sum(nums1)+sum(nums2) + # + if nums1[-1] <= nums2[0]: + print 'in 7' + return self.find_median(nums1 + nums2) + # + if nums2[-1] <= nums1[0]: + print 'in 8' + return self.find_median(nums2 + nums1) + # + median1 = self.find_median(nums1) + median2 = self.find_median(nums2) + if median1 < median2: + print 'in 9' + return self.findMedianSortedArrays(nums1[(smaller_len-1)//2:], nums2[:(len(nums2)) - (smaller_len-1)//2]) + elif median1 == median2: + print 'in 10' + return median1 + else: + print 'in 11' + return self.findMedianSortedArrays(nums2[(smaller_len-1)//2:], nums1[:(len(nums1)) - (smaller_len-1)//2]) + # + if len(nums1) == 0: + print 'in 1' + return self.find_median(nums2) + # + if len(nums2) == 0: + print 'in 2' + return self.find_median(nums1) + # + if len(nums1) == 1: + print 'in 3' + bisect.insort(nums2, nums1[0]) + return self.find_median(nums2) + # + if len(nums2) == 1: + print 'in 4' + bisect.insort(nums1, nums2[0]) + return self.find_median(nums1) + # + if len(nums1) == 2: + print 'in 5' + bisect.insort(nums2, nums1[0]) + bisect.insort(nums2, nums1[1]) + return self.find_median(nums2) + # + if len(nums2) == 2: + print 'in 6' + bisect.insort(nums1, nums2[0]) + bisect.insort(nums1, nums2[1]) + return self.find_median(nums1) + # + def find_median(self,a): + if len(a) % 2 ==0: + return (a[len(a)//2]+a[len(a)//2-1]) / 2.0 + else: + return a[len(a)//2] + + +# Optimised & Cleaned +import bisect +class Solution(object): + def findMedianSortedArrays(self, nums1, nums2): + ## General Cases + if len(nums1) > 2 and len(nums2) > 2: + print nums1, nums2 + print len(nums1),len(nums2) + smaller_len = min(len(nums1),len(nums2)) + if nums1[-1] <= nums2[0]: + return self.find_median(nums1 + nums2) + if nums2[-1] <= nums1[0]: + return self.find_median(nums2 + nums1) + median1 = self.find_median(nums1) + median2 = self.find_median(nums2) + if median1 < median2: + return self.findMedianSortedArrays(nums1[(smaller_len-1)//2:], nums2[:(len(nums2)) - (smaller_len-1)//2]) + elif median1 == median2: + return median1 + else: + return self.findMedianSortedArrays(nums2[(smaller_len-1)//2:], nums1[:(len(nums1)) - (smaller_len-1)//2]) + ## Base cases + if len(nums1) == 0: + return self.find_median(nums2) + if len(nums2) == 0: + return self.find_median(nums1) + if len(nums1) == 1: + bisect.insort(nums2, nums1[0]) + return self.find_median(nums2) + if len(nums2) == 1: + bisect.insort(nums1, nums2[0]) + return self.find_median(nums1) + if len(nums1) == 2: + bisect.insort(nums2, nums1[0]) + bisect.insort(nums2, nums1[1]) + return self.find_median(nums2) + if len(nums2) == 2: + bisect.insort(nums1, nums2[0]) + bisect.insort(nums1, nums2[1]) + return self.find_median(nums1) + # + def find_median(self,a): + if len(a) % 2 ==0: + return (a[len(a)//2]+a[len(a)//2-1]) / 2.0 + else: + return a[len(a)//2] + +a = Solution() +a.findMedianSortedArrays([1,2,3],[2,3,4,5,6,7,8,9]) + + + if (len(nums1)+len(nums2)) % 2 = 0: + + if (len(nums1)+len(nums2)) % 2 = 1: + + +def a(b): + if len(b) ==1: + print 'end' + return 0 + print '\n\n\n' + print b, len(b) + a(b[:len(b)//2]) + return 0 + + +a([1,2,3,4,5,6,7,8]) + + +if 2==1: + print 'ok' +elif 1==1: + print 'ok2' +else: + print 'no' diff --git a/5. Longest Palindromic Substring.py b/5. Longest Palindromic Substring.py new file mode 100644 index 0000000..4ba1604 --- /dev/null +++ b/5. Longest Palindromic Substring.py @@ -0,0 +1,99 @@ +Palindromic 回文结构的 + +# Too slow +class Solution(object): + def longestPalindrome(self, s): + """ + :type s: str + :rtype: str + """ + i=0 + l=len(s) + max_substring_len=0 + max_substring='' + for i in range(0,l): + for j in range(i,l): + check=0 + for k in range(i,(i+j-1)/2+1): + if s[k] != s[i+j-k]: + check=1 + break + if check == 0 and j-i+1 > max_substring_len: + max_substring_len = j-i+1 + max_substring = s[i:j+1] + return max_substring + + +# a bit slow, dynamic programming (recursion) +class Solution(object): + def longestPalindrome(self, s): + """ + :type s: str + :rtype: str + """ + i=0 + l=len(s) + marks=[[None]*l for i in range(0,l)] + max_substring_len=0 + max_substring='' + for i in range(0,l): + marks[i][i] = True + for i in range(0,l-1): + marks[i][i+1] = (s[i] == s[i+1]) + for i in range(0,l): + for j in range(i,l): + if (j-i+1 > max_substring_len) and self.is_Palindrome(s,i,j,marks): + max_substring_len = j-i+1 + max_substring = s[i:j+1] + + return max_substring + + def is_Palindrome(self,s,i,j,marks): + marks[i][j] = ((marks[i][j]) or (s[i] == s[j])) and ((j-i<2) or (marks[i+1][j-1] or self.is_Palindrome(s,i+1,j-1,marks))) + return marks[i][j] + + +# Accepted, Expand Around Center +class Solution(object): + def longestPalindrome(self, s): + """ + :type s: str + :rtype: str + """ + i=0 + l=len(s) + marks=[[None]*l for i in range(0,l)] + max_substring_len=0 + max_substring='' + # start with 1 char + for i in range(0,l): + ia=ib=i + flag = True + while ia>=0 and ib <= l-1 and flag == True: + if s[ia]==s[ib]: + if ib-ia+1 > max_substring_len: + max_substring_len = ib-ia+1 + max_substring = s[ia:ib+1] + ia=ia-1 + ib=ib+1 + else: + flag = False + + # start with 2 char + for i in range(0,l-1): + ia=i + ib=i+1 + flag = True + while ia>=0 and ib <= l-1 and flag == True: + if s[ia]==s[ib]: + if ib-ia+1 > max_substring_len: + max_substring_len = ib-ia+1 + max_substring = s[ia:ib+1] + ia=ia-1 + ib=ib+1 + else: + flag = False + + return max_substring + + diff --git a/6. ZigZag Conversion.py b/6. ZigZag Conversion.py new file mode 100644 index 0000000..c80e92c --- /dev/null +++ b/6. ZigZag Conversion.py @@ -0,0 +1,39 @@ +class Solution(object): + def convert(self, s, numRows): + """ + :type s: str + :type numRows: int + :rtype: str + """ + l = ['' for i in range(numRows)] + # c = 0 + r = 0 + direction = 0 + count = 0 + max_count=len(s) + while count < max_count: + l[r] = l[r] + s[count] + if direction == 0: + if r < numRows-1: + r = r + 1 + else: + r = r - 1 + # c = c + 1 + direction = 1 + else: + if r > 0: + r = r - 1 + else: + r = r + 1 + # c = c + 1 + direction = 0 + count = count + 1 + # + result='' + for i in range(numRows): + result = result + l[i] + return result + +a=Solution() +print a.convert("PAYPALISHIRING",3) + diff --git a/7. Reverse Integer.py b/7. Reverse Integer.py new file mode 100644 index 0000000..c566a9f --- /dev/null +++ b/7. Reverse Integer.py @@ -0,0 +1,22 @@ +class Solution(object): + def reverse(self, x): + """ + :type x: int + :rtype: int + """ + if x<0: + sign = -1 + x = x * -1 + else: + sign = 1 + s = str(x) + s2 = '' + l = len(s) + for i in range(l): + s2=s2+s[l-1-i] + if len(s2) > 10: + return 0 + if (len(s2) == 10) and ((sign == -1 and s2 > '2147483648') or (sign == 1 and s2 > '2147483647')): + return 0 + result = int(s2)*sign + return result \ No newline at end of file diff --git a/8. String to Integer (atoi).py b/8. String to Integer (atoi).py new file mode 100644 index 0000000..4914900 --- /dev/null +++ b/8. String to Integer (atoi).py @@ -0,0 +1,49 @@ +class Solution(object): + def myAtoi(self, str): + """ + :type str: str + :rtype: int + """ + # while len(str)>=1: + # if str[0] == ' ': + # str=str[1:] + # else: + # break + str = str.lstrip() + sign = 1 + if len(str) == 0: + return 0 + if str[0] == '-': + sign = -1 + str = str[1:] + elif str[0] == '+': + sign = 1 + str = str[1:] + i=0 + while len(str)>=1: + if str[0] == '0': + str=str[1:] + else: + break + if len(str) == 0: + return 0 + if not (str[0]>='0' and str[0]<='9'): + return 0 + i=0 + while i < 12 and i < len(str): + if not (str[i]>='0' and str[i]<='9'): + str = str[:i] + break + i=i+1 + if (len(str)==10): + if (sign == -1 and str > '2147483648'): + return -2147483648 + if (sign == 1 and str > '2147483647'): + return 2147483647 + if (len(str)>10): + if (sign == -1): + return -2147483648 + if (sign == 1): + return 2147483647 + result = int(str)*sign + return result diff --git a/9. Palindrome Number.py b/9. Palindrome Number.py new file mode 100644 index 0000000..ad3325e --- /dev/null +++ b/9. Palindrome Number.py @@ -0,0 +1,36 @@ +# convert to string +class Solution(object): + def isPalindrome(self, x): + """ + :type x: int + :rtype: bool + """ + x=str(x) + for i in range(len(x)/2): + if x[i] != x[len(x)-1-i]: + return False + return True + + +# not convert to string +import math +class Solution(object): + def isPalindrome(self, x): + """ + :type x: int + :rtype: bool + """ + if x < 0: + return False + if x==0: + return True + i=0 + while math.log10(x)/2 >= i: + a = x/(10**i)%10 + b = x/(10**(int(math.log10(x))-i))%10 + if a != b : + return False + i = i + 1 + return True + +