diff --git a/11.container-with-most-water.py b/11.container-with-most-water.py new file mode 100644 index 00000000..91da2cd1 --- /dev/null +++ b/11.container-with-most-water.py @@ -0,0 +1,59 @@ +# +# @lc app=leetcode id=11 lang=python +# +# [11] Container With Most Water +# +# https://leetcode.com/problems/container-with-most-water/description/ +# +# algorithms +# Medium (42.47%) +# Total Accepted: 320.1K +# Total Submissions: 751.3K +# Testcase Example: '[1,8,6,2,5,4,8,3,7]' +# +# Given n non-negative integers a1, a2, ..., an , where each represents a point +# at coordinate (i, ai). n vertical lines are drawn such that the two endpoints +# of line i is at (i, ai) and (i, 0). Find two lines, which together with +# x-axis forms a container, such that the container contains the most water. +# +# Note: You may not slant the container and n is at least 2. +# +# +# +# +# +# The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In +# this case, the max area of water (blue section) the container can contain is +# 49. +# +# +# +# Example: +# +# +# Input: [1,8,6,2,5,4,8,3,7] +# Output: 49 +# +# +class Solution(object): + def maxArea(self, height): + """ + :type height: List[int] + :rtype: int + """ + max_area = 0 + head = 0 + tail = len(height) - 1 + # Calculating the area by moving two pointers in bi-direction. + while (tail > head): + area = min([height[head], height[tail]])*(tail-head) + if area > max_area: + max_area = area + if height[head] > height[tail]: + tail = tail - 1 + else: + head = head + 1 + + return max_area + + diff --git a/12.integer-to-roman.py b/12.integer-to-roman.py new file mode 100644 index 00000000..7aa06df3 --- /dev/null +++ b/12.integer-to-roman.py @@ -0,0 +1,127 @@ +# +# @lc app=leetcode id=12 lang=python +# +# [12] Integer to Roman +# +# https://leetcode.com/problems/integer-to-roman/description/ +# +# algorithms +# Medium (49.70%) +# Total Accepted: 204.4K +# Total Submissions: 410.8K +# Testcase Example: '3' +# +# Roman numerals are represented by seven different symbols: I, V, X, L, C, D +# and M. +# +# +# Symbol Value +# I 1 +# V 5 +# X 10 +# L 50 +# C 100 +# D 500 +# M 1000 +# +# For example, two is written as II in Roman numeral, just two one's added +# together. Twelve is written as, XII, which is simply X + II. The number +# twenty seven is written as XXVII, which is XX + V + II. +# +# Roman numerals are usually written largest to smallest from left to right. +# However, the numeral for four is not IIII. Instead, the number four is +# written as IV. Because the one is before the five we subtract it making four. +# The same principle applies to the number nine, which is written as IX. There +# are six instances where subtraction is used: +# +# +# 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. +# +# +# Given an integer, convert it to a roman numeral. Input is guaranteed to be +# within the range from 1 to 3999. +# +# Example 1: +# +# +# Input: 3 +# Output: "III" +# +# Example 2: +# +# +# Input: 4 +# Output: "IV" +# +# Example 3: +# +# +# Input: 9 +# Output: "IX" +# +# Example 4: +# +# +# Input: 58 +# Output: "LVIII" +# Explanation: L = 50, V = 5, III = 3. +# +# +# Example 5: +# +# +# Input: 1994 +# Output: "MCMXCIV" +# Explanation: M = 1000, CM = 900, XC = 90 and IV = 4. +# +# +class Solution(object): + def intToRoman(self, num): + """ + :type num: int + :rtype: str + """ + tbl = {1:'I', 5:'V', 10:'X', 50:'L', 100:'C', 500:'D', 1000:'M'} + num_lst = [] + while num != 0: + tmp = num % 10 + num_lst.append(tmp) + num = num / 10 + x = 1 + res = [] + for num in num_lst: + if num >3 and num <9: + key_1 = 5 + else: + key_1 = 1 + prim_key = key_1 * x + prim_val = tbl[prim_key] + minor_val = tbl[x] # I, X, C, M + tmp_str = '' + cmp_key = num + if cmp_key==4 or cmp_key==9: + if cmp_key == 9: + prim_val = tbl[prim_key*10] + tmp_str = minor_val + prim_val # minor, primal + elif cmp_key<=3: + for i in range(cmp_key): + tmp_str = tmp_str + minor_val # primal, primal, primal + + elif cmp_key>5 and cmp_key<=8: + # primal, minor,... + tmp_str = prim_val + for i in range(cmp_key-5): + tmp_str = tmp_str + minor_val + elif cmp_key == 5: + tmp_str = prim_val + res.append(tmp_str) + x = x * 10 + res = res[::-1] + res = ''.join(res) + return res + + + + diff --git a/15.3-sum.py b/15.3-sum.py new file mode 100644 index 00000000..d35ef20e --- /dev/null +++ b/15.3-sum.py @@ -0,0 +1,90 @@ +# +# @lc app=leetcode id=15 lang=python +# +# [15] 3Sum +# +# https://leetcode.com/problems/3sum/description/ +# +# algorithms +# Medium (23.34%) +# Total Accepted: 485.6K +# Total Submissions: 2.1M +# Testcase Example: '[-1,0,1,2,-1,-4]' +# +# Given an array nums of n integers, are there elements a, b, c in nums such +# that a + b + c = 0? Find all unique triplets in the array which gives the sum +# of zero. +# +# Note: +# +# The solution set must not contain duplicate triplets. +# +# Example: +# +# +# Given array nums = [-1, 0, 1, 2, -1, -4], +# +# A solution set is: +# [ +# ⁠ [-1, 0, 1], +# ⁠ [-1, -1, 2] +# ] +# +# +# +''' +class Solution(object): + def threeSum(self, nums): + """ + :type nums: List[int] + :rtype: List[List[int]] + """ + nums_len = len(nums) + visible_ids = [] + for i in range(nums_len): + + j = i + 1 + while j < nums_len: + arr_col = nums[i] + nums[j] + if -arr_col in nums[j+1:]: + ids_set = [nums[i], nums[j], -arr_col] + ids_set.sort() + if ids_set not in visible_ids: + visible_ids.append(ids_set) + j = j + 1 + return visible_ids +''' +class Solution(object): + + def threeSum(self, nums): + """ + :type nums: List[int] + :rtype: List[List[int]] + """ + nums_len = len(nums) + if nums_len < 3: + return [] + nums.sort() + visible_ids = [] + for i in range(nums_len-2): + if i >0 and nums[i] == nums[i-1]: + continue + head, tail = i+1, nums_len-1 + + while head < tail: + sum_res = nums[head] + nums[tail] + nums[i] + if sum_res < 0: + head += 1 + elif sum_res > 0: + tail -= 1 + else: + visible_ids.append((nums[head], nums[tail], nums[i])) + while headhead and nums[tail] == nums[tail-1]: + tail -= 1 + head += 1 + tail -= 1 + return visible_ids + + diff --git a/16.3-sum-closest.py b/16.3-sum-closest.py new file mode 100644 index 00000000..3138e210 --- /dev/null +++ b/16.3-sum-closest.py @@ -0,0 +1,60 @@ +# +# @lc app=leetcode id=16 lang=python +# +# [16] 3Sum Closest +# +# https://leetcode.com/problems/3sum-closest/description/ +# +# algorithms +# Medium (38.77%) +# Total Accepted: 286K +# Total Submissions: 704.1K +# Testcase Example: '[-1,2,1,-4]\n1' +# +# Given an array nums of n integers and an integer target, find three integers +# in nums such that the sum is closest to target. Return the sum of the three +# integers. You may assume that each input would have exactly one solution. +# +# Example: +# +# +# Given array nums = [-1, 2, 1, -4], and target = 1. +# +# The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). +# +# +# +class Solution(object): + def threeSumClosest(self, nums, target): + """ + :type nums: List[int] + :type target: int + :rtype: int + """ + nums_len = len(nums) + if nums_len < 3: + return [] + nums.sort() + visible_ids = [] + closest = target + margin = 9999 + sum_res = 0 + for i in range(nums_len-2): + if i >0 and nums[i] == nums[i-1]: + continue + head, tail = i+1, nums_len-1 + + while head < tail: + sum_res = nums[head] + nums[tail] + nums[i] + tmp_margin = max(sum_res, target) - min(sum_res, target) + if tmp_margin < margin: + margin = tmp_margin + closest = sum_res + if sum_res < target: + head += 1 + elif sum_res > target: + tail -= 1 + else: + return sum_res + return closest + diff --git a/17.letter-combinations-of-a-phone-number.py b/17.letter-combinations-of-a-phone-number.py new file mode 100644 index 00000000..5367321e --- /dev/null +++ b/17.letter-combinations-of-a-phone-number.py @@ -0,0 +1,42 @@ +# +# @lc app=leetcode id=17 lang=python +# +# [17] Letter Combinations of a Phone Number +# +# https://leetcode.com/problems/letter-combinations-of-a-phone-number/description/ +# +# algorithms +# Medium (40.29%) +# Total Accepted: 348.2K +# Total Submissions: 862K +# Testcase Example: '"23"' +# +# Given a string containing digits from 2-9 inclusive, return all possible +# letter combinations that the number could represent. +# +# A mapping of digit to letters (just like on the telephone buttons) is given +# below. Note that 1 does not map to any letters. +# +# +# +# Example: +# +# +# Input: "23" +# Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. +# +# +# Note: +# +# Although the above answer is in lexicographical order, your answer could be +# in any order you want. +# +# +class Solution(object): + def letterCombinations(self, digits): + """ + :type digits: str + :rtype: List[str] + """ + + diff --git a/18.4-sum.py b/18.4-sum.py new file mode 100644 index 00000000..3fb3d94c --- /dev/null +++ b/18.4-sum.py @@ -0,0 +1,265 @@ +# +# @lc app=leetcode id=18 lang=python +# +# [18] 4Sum +# +# https://leetcode.com/problems/4sum/description/ +# +# algorithms +# Medium (29.63%) +# Total Accepted: 212.7K +# Total Submissions: 715.9K +# Testcase Example: '[1,0,-1,0,-2,2]\n0' +# +# Given an array nums of n integers and an integer target, are there elements +# a, b, c, and d in nums such that a + b + c + d = target? Find all unique +# quadruplets in the array which gives the sum of target. +# +# Note: +# +# The solution set must not contain duplicate quadruplets. +# +# Example: +# +# +# Given array nums = [1, 0, -1, 0, -2, 2], and target = 0. +# +# A solution set is: +# [ +# ⁠ [-1, 0, 0, 1], +# ⁠ [-2, -1, 1, 2], +# ⁠ [-2, 0, 0, 2] +# ] +# +# +# +''' +class Solution(object): + def fourSum(self, nums, target): + """ + :type nums: List[int] + :type target: int + :rtype: List[List[int]] + """ + result_mat = [] + s_mat = [] + arr_res = [] + s_len = len(nums) + # sort the nums + nums.sort() + # create a matrix, each elem denotes the sum of 2 numbers. + sum_mat = [] + arr_col = [0]*s_len + for i in range(s_len): + j = i + 1 + while j < s_len: + arr_col[j] = nums[i] + nums[j] + j = j + 1 + if i < s_len-1: + s_mat.append(arr_col) + arr_col = [0]*s_len + + # trival the matrix and find the sum of 4 elems that equal to target number. + for row in range(s_len-1): + col = row + 1 + if col == s_len - 1: + break + while col < s_len - 1 and s_mat[row][col] == s_mat[row][col+1]: + col = col + 1 + + header = [row, col] + tail = [s_len-2, s_len-1] + arr_res.append([header, tail]) + while header[0] < tail[0] and header[1] target: + if tail[1]-1 > tail[0]: + if tail[1]-1 == header[0]: + tail[0] -= tail[0] + + else: + tmp_arr = [nums[header[0]], nums[header[1]], nums[tail[0]], nums[tail[1]]] + tmp_arr.sort() + if tmp_arr not in result_mat: + result_mat.append(tmp_arr) + + header[1] += 1 + #tail[0] -= 1 + + + + return arr_res + + +class Solution(object): + def fourSum(self, nums, target): + """ + :type nums: List[int] + :type target: int + :rtype: List[List[int]] + """ + result_mat = [] + s_mat = [] + arr_res = [] + s_len = len(nums) + # sort the nums + nums.sort() + # create a matrix, each elem denotes the sum of 2 numbers. + sum_mat = [] + arr_col = [0]*s_len + for i in range(s_len): + j = i + 1 + while j < s_len: + arr_col[j] = nums[i] + nums[j] + j = j + 1 + if i < s_len-1: + s_mat.append(arr_col) + arr_col = [0]*s_len + + # trival the matrix and find the sum of 4 elems that equal to target number. + for row in range(s_len-1): + col = row + 1 + if col == s_len - 1: + break + # first loop + while col < s_len: + row_2 = row + 1 + # second loop + while row_2 < s_len-1: + # thrid loop + col_2 = row_2 + 1 + while col_2 < s_len: + if col_2 == col or row == col_2 or row_2 == col: + col_2 += 1 + continue + tmp_sum = s_mat[row][col] + s_mat[row_2][col_2] + if tmp_sum == target: + tmp_arr = [nums[row], nums[col], nums[row_2], nums[col_2]] + tmp_arr.sort() + if tmp_arr not in result_mat: + result_mat.append(tmp_arr) + col_2 += 1 + row_2 += 1 + col += 1 + return result_mat + ''' +class Solution(object): + def fourSum(self, nums, target): + """ + :type nums: List[int] + :type target: int + :rtype: List[List[int]] + """ + result_mat = [] + s_mat = [] + arr_res = [] + s_len = len(nums) + # sort the nums + nums.sort() + # create a matrix, each elem denotes the sum of 2 numbers. + sum_mat = [] + arr_col = [0]*s_len + for i in range(s_len): + j = i + 1 + while j < s_len: + arr_col[j] = nums[i] + nums[j] + j = j + 1 + if i < s_len-1: + s_mat.append(arr_col) + arr_col = [0]*s_len + + # trival the matrix and find the sum of 4 elems that equal to target number. + for row in range(s_len-1): + col = row + 1 + while col < s_len: + row_1 = row + 1 + col_1 = col + 1 + header = s_mat[row][col] + if col-1==row: + tail = s_mat[row+1][col+1] + else: + left = header + s_mat[row+1][col-1] + right = header + s_mat[row+1][col+1] + left_res = max(left, target) - min(left, target) + right_res = max(right, target) - min(right, target) + if left_res < right: + tail = left + col_1 = col - 1 + else: + tail = right + sw = True + while sw: + tmp_tail_left = None + tmp_tail_right = None + tmp_tail_down = None + if col_1 < col: + + if col_1 - 1 != row_1: + tmp_tail_left = s_mat[row_1][col_1-1] + if row_1 + 1 != col_1: + tmp_tail_down = s_mat[row_1+1][col_1] + if tmp_tail_left!=None and tmp_tail_down!=None: + # calculate the margin + left_res = max(tmp_tail_left, target) - min(tmp_tail_left, target) + down_res = max(tmp_tail_down, target) - min(tmp_tail_down, target) + + if left_res == 0: + result_mat.append(nums[row], nums[col], nums[row_1], nums[col-1]) + elif down_res == 0: + result_mat.append(nums[row], nums[col], nums[row_1+1], nums[col_1]) + + if left_res < right_res: + tail = tmp_tail_left + col_1 -= 1 + else: + tail = tmp_tail_down + row_1 += 1 + + + elif tmp_tail_left is None and tmp_tail_down!=None: + tail = tmp_tail_down + elif tmp_tail_left!=None and tmp_tail_down is None: + tail = tmp_tail_left + else: + sw = False + else: + if col_1 + 1 != s_len: + tmp_tail_right = s_mat[row_1][col_1+1] + if row_1 + 1 != s_len - 1: + tmp_tail_down = s_mat[row_1+1][col_1] + + if tmp_tail_left!=None and tmp_tail_down!=None: + # calculate the margin + right_res = max(tmp_tail_right, target) - min(tmp_tail_right, target) + down_res = max(tmp_tail_down, target) - min(tmp_tail_down, target) + + if right_res == 0: + result_mat.append(nums[row], nums[col], nums[row_1], nums[col+1]) + elif down_res == 0: + result_mat.append(nums[row], nums[col], nums[row_1+1], nums[col_1]) + + if right_res < down_res: + tail = tmp_tail_right + col_1 += 1 + else: + tail = tmp_tail_down + row_1 += 1 + + + elif tmp_tail_right is None and tmp_tail_down!=None: + tail = tmp_tail_down + elif tmp_tail_right!=None and tmp_tail_down is None: + tail = tmp_tail_right + else: + sw = False + return result_mat + + 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 00000000..b1866019 --- /dev/null +++ b/19.remove-nth-node-from-end-of-list.py @@ -0,0 +1,72 @@ +# +# @lc app=leetcode id=19 lang=python +# +# [19] Remove Nth Node From End of List +# +# https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/ +# +# algorithms +# Medium (33.96%) +# Total Accepted: 357.3K +# Total Submissions: 1.1M +# Testcase Example: '[1,2,3,4,5]\n2' +# +# 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 + +class Solution(object): + def removeNthFromEnd(self, head, n): + """ + :type head: ListNode + :type n: int + :rtype: ListNode + """ + lst_len = 0 + head_node = ListNode(None) + head_node.next = head + tail = head + while tail != None: + tail = tail.next + lst_len += 1 + if n > lst_len: + head_node = head_node.next + return head_node + pos = lst_len - n + cnt = 0 + tail = head_node.next + pre = head_node + while cnt < pos: + pre = tail + tail = tail.next + cnt += 1 + pre.next = tail.next + head_node = head_node.next + return head_node + + + + diff --git a/2.add-two-numbers.c b/2.add-two-numbers.c new file mode 100644 index 00000000..535def1f --- /dev/null +++ b/2.add-two-numbers.c @@ -0,0 +1,104 @@ +/* + * @lc app=leetcode id=2 lang=c + * + * [2] Add Two Numbers + * + * https://leetcode.com/problems/add-two-numbers/description/ + * + * algorithms + * Medium (30.54%) + * Total Accepted: 764K + * Total Submissions: 2.5M + * Testcase Example: '[2,4,3]\n[5,6,4]' + * + * You are given two non-empty linked lists representing two non-negative + * integers. The digits are stored in reverse order and each of their nodes + * contain a single digit. Add the two numbers and return it as a linked list. + * + * You may assume the two numbers do not contain any leading zero, except the + * number 0 itself. + * + * Example: + * + * + * Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) + * Output: 7 -> 0 -> 8 + * Explanation: 342 + 465 = 807. + * + * + */ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * struct ListNode *next; + * }; + */ +void reverse_list(struct ListNode* lst){ + ListNode *head = lst; + ListNode *end = lst; + while(end->next != NULL){ + ListNode* tmp = end->next; + end->next = tmp->next; + tmp->next = head; + head = tmp; + } +} +struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) { + // reverse the given listes. + reverse_list(l1); + reverse_list(l2); + ListNode* l1_node = l1; + ListNode* l2_node = l2; + ListNode* sum_lst = new ListNode(); + sum_lst->val = 0; + sum_lst->next = NULL; + ListNode* sum_node = sum_lst; + + while(l1_node != NULL && l2_node != NULL){ + int sum_val = l1_node->val + l2_node->val; + int pos1_val = sum_val % 10; + int pos2_val = sum_val / 10; + sum_node->val = pos1_val; + ListNode* tmp_node = new ListNode(); + tmp_node->val = pos2_val; + tmp_node->next = sum_node; + sum_node = tmp_node; + + l1_node = l1_node->next; + l2_node = l2_node->next; + } + ListNode* retail = NULL; + if (l1_node == NULL){ + retail = l2_node; + } + else if (l2_node == NULL){ + retail = l1_node; + } + else{ + if(sum_node->val == 0){ + sum_node = sum_node->next; + } + return sum_node; + } + + while(retail != NULL){ + int sum_val = sum_node->val + retail->val; + int pos1_val = sum_val % 10; + int pos2_val = sum_val / 10; + + sum_node->val = pos1_val; + ListNode* tmp_node = new ListNode(); + tmp_node->val = pos2_val; + tmp_node->next = sum_node; + sum_node = tmp_node; + + retail = retail->next; + } + + if (sum_node->val == 0){ + sum_node = sum_node->next; + } + return sum_node; +} + diff --git a/2.add-two-numbers.py b/2.add-two-numbers.py new file mode 100644 index 00000000..da77a61d --- /dev/null +++ b/2.add-two-numbers.py @@ -0,0 +1,99 @@ +# +# @lc app=leetcode id=2 lang=python3 +# +# [2] Add Two Numbers +# +# https://leetcode.com/problems/add-two-numbers/description/ +# +# algorithms +# Medium (30.54%) +# Total Accepted: 764K +# Total Submissions: 2.5M +# Testcase Example: '[2,4,3]\n[5,6,4]' +# +# You are given two non-empty linked lists representing two non-negative +# integers. The digits are stored in reverse order and each of their nodes +# contain a single digit. Add the two numbers and return it as a linked list. +# +# You may assume the two numbers do not contain any leading zero, except the +# number 0 itself. +# +# Example: +# +# +# Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) +# Output: 7 -> 0 -> 8 +# Explanation: 342 + 465 = 807. +# +# +# +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None + +class Solution: + def reverse_list(self, lst): + ''' + Reverse the given list. + ''' + end = lst + head = ListNode(end.val) + end = end.next + while end is not None: + tmp = ListNode(end.val) + tmp.next = head + head = tmp + end = end.next + return head + + def addTwoNumbers(self, l1, l2): + l3_head = ListNode(None) + l3 = ListNode(0) + l3_head.next = l3 + pre = l3 + # Reverge the input number list + #l1 = self.reverse_list(l1) + #l2 = self.reverse_list(l2) + + # Trival l1&l2, create a new list to saving the sum of l1&l2. + + l1_end = l1 + l2_end = l2 + while l1_end is not None and l2_end is not None: + sum_res = l1_end.val + l2_end.val + l3.val + l3.val = sum_res % 10 + end = ListNode(sum_res/10) + l1_end = l1_end.next + l2_end = l2_end.next + pre = l3 + l3.next = end + l3 = end + + retail_lst = None + if l2_end is None: + retail_lst = l1_end + + elif l1_end is None: + retail_lst = l2_end + + if retail_lst is None: + if l3.val == 0: + pre.next = None + l3 = None + return l3_head.next + + while retail_lst is not None: + sum_res = l3.val + retail_lst.val + l3.val = sum_res % 10 + end = ListNode(sum_res/10) + retail_lst = retail_lst.next + pre = l3 + l3.next = end + l3 = end + if l3.val == 0: + l3 = None + pre.next = None + return l3_head.next + diff --git a/22.generate-parentheses.py b/22.generate-parentheses.py new file mode 100644 index 00000000..21806558 --- /dev/null +++ b/22.generate-parentheses.py @@ -0,0 +1,51 @@ +# +# @lc app=leetcode id=22 lang=python +# +# [22] Generate Parentheses +# +# https://leetcode.com/problems/generate-parentheses/description/ +# +# algorithms +# Medium (53.04%) +# Total Accepted: 304K +# Total Submissions: 570.9K +# Testcase Example: '3' +# +# +# Given n pairs of parentheses, write a function to generate all combinations +# of well-formed parentheses. +# +# +# +# For example, given n = 3, a solution set is: +# +# +# [ +# ⁠ "((()))", +# ⁠ "(()())", +# ⁠ "(())()", +# ⁠ "()(())", +# ⁠ "()()()" +# ] +# +# +class Solution(object): + def solver(self, result, cur_str, left, right): + if left==0 and right==0: + result.append(cur_str) + return + if left > 0: + self.solver(result, cur_str+'(', left-1, right) + if right > 0 and right > left: + self.solver(result, cur_str+')', left, right-1) + def generateParenthesis(self, n): + """ + :type n: int + :rtype: List[str] + """ + result = [] + if n <= 0: + return result + self.solver(result, '', n, n) + return result + diff --git a/24.swap-nodes-in-pairs.py b/24.swap-nodes-in-pairs.py new file mode 100644 index 00000000..59798d84 --- /dev/null +++ b/24.swap-nodes-in-pairs.py @@ -0,0 +1,59 @@ +# +# @lc app=leetcode id=24 lang=python +# +# [24] Swap Nodes in Pairs +# +# https://leetcode.com/problems/swap-nodes-in-pairs/description/ +# +# algorithms +# Medium (43.04%) +# Total Accepted: 284K +# Total Submissions: 656.5K +# Testcase Example: '[1,2,3,4]' +# +# Given a linked list, swap every two adjacent nodes and return its head. +# +# You may not modify the values in the list's nodes, only nodes itself may be +# changed. +# +# +# +# Example: +# +# +# Given 1->2->3->4, you should return the list as 2->1->4->3. +# +# +# +# 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 + """ + if head is None or head.next is None: + return head + head_node = ListNode(None) + head_node.next = head + pre = head_node + tail = head.next + cnt = 0 + while tail != None: + if cnt % 2 == 0: + tmp = pre.next + tmp.next = tail.next + tail.next = tmp + pre.next = tail + tail = tmp + pre = pre.next + tail = tail.next + cnt += 1 + head_node = head_node.next + return head_node + diff --git a/29.divide-two-integers.py b/29.divide-two-integers.py new file mode 100644 index 00000000..f154f8cc --- /dev/null +++ b/29.divide-two-integers.py @@ -0,0 +1,62 @@ +# +# @lc app=leetcode id=29 lang=python +# +# [29] Divide Two Integers +# +# https://leetcode.com/problems/divide-two-integers/description/ +# +# algorithms +# Medium (16.04%) +# Total Accepted: 181.4K +# Total Submissions: 1.1M +# Testcase Example: '10\n3' +# +# Given two integers dividend and divisor, divide two integers without using +# multiplication, division and mod operator. +# +# Return the quotient after dividing dividend by divisor. +# +# The integer division should truncate toward zero. +# +# Example 1: +# +# +# Input: dividend = 10, divisor = 3 +# Output: 3 +# +# Example 2: +# +# +# Input: dividend = 7, divisor = -3 +# Output: -2 +# +# Note: +# +# +# Both dividend and divisor will be 32-bit signed integers. +# The divisor will never be 0. +# Assume we are dealing with an environment which could only store integers +# within the 32-bit signed integer range: [−231,  231 − 1]. For the purpose of +# this problem, assume that your function returns 231 − 1 when the division +# result overflows. +# +# +# +class Solution(object): + def divide(self, dividend, divisor): + """ + :type dividend: int + :type divisor: int + :rtype: int + """ + res = dividend / divisor + if res > 2147483647: + return 2147483647 + if res < 0: + if dividend % divisor != 0: + res = res + 1 + if res < -2147483648: + return -2147483648 + return res + + diff --git a/3.longest-substring-without-repeating-characters.py b/3.longest-substring-without-repeating-characters.py new file mode 100644 index 00000000..6e7d6c2a --- /dev/null +++ b/3.longest-substring-without-repeating-characters.py @@ -0,0 +1,67 @@ +# +# @lc app=leetcode id=3 lang=python +# +# [3] Longest Substring Without Repeating Characters +# +# https://leetcode.com/problems/longest-substring-without-repeating-characters/description/ +# +# algorithms +# Medium (27.53%) +# Total Accepted: 808.1K +# Total Submissions: 2.9M +# Testcase Example: '"abcabcbb"' +# +# Given a string, find the length of the longest substring without repeating +# characters. +# +# +# Example 1: +# +# +# Input: "abcabcbb" +# Output: 3 +# Explanation: The answer is "abc", with the length of 3. +# +# +# +# Example 2: +# +# +# Input: "bbbbb" +# Output: 1 +# Explanation: The answer is "b", with the length of 1. +# +# +# +# Example 3: +# +# +# Input: "pwwkew" +# Output: 3 +# Explanation: The answer is "wke", with the length of 3. +# ⁠ Note that the answer must be a substring, "pwke" is a +# subsequence and not a substring. +# +# +# +# +# +# +class Solution(object): + def lengthOfLongestSubstring(self, s): + """ + :type s: str + :rtype: int + """ + s_len = len(s) + ans = 0 + hash_map = {} + i = 0 + j = 0 + while j < s_len: + if s[j] in hash_map.keys(): + i = max(hash_map[s[j]], i) + ans = max(ans, j - i + 1) + hash_map[s[j]] = j + 1 + j = j + 1 + return ans diff --git a/31.next-permutation.py b/31.next-permutation.py new file mode 100644 index 00000000..e6ea0fe2 --- /dev/null +++ b/31.next-permutation.py @@ -0,0 +1,37 @@ +# +# @lc app=leetcode id=31 lang=python +# +# [31] Next Permutation +# +# https://leetcode.com/problems/next-permutation/description/ +# +# algorithms +# Medium (30.02%) +# Total Accepted: 215.6K +# Total Submissions: 717.2K +# Testcase Example: '[1,2,3]' +# +# Implement next permutation, which rearranges numbers into the +# lexicographically next greater permutation of numbers. +# +# If such arrangement is not possible, it must rearrange it as the lowest +# possible order (ie, sorted in ascending order). +# +# The replacement must be in-place and use only constant extra memory. +# +# Here are some examples. Inputs are in the left-hand column and its +# corresponding outputs are in the right-hand column. +# +# 1,2,3 → 1,3,2 +# 3,2,1 → 1,2,3 +# 1,1,5 → 1,5,1 +# +# +class Solution(object): + def nextPermutation(self, nums): + """ + :type nums: List[int] + :rtype: None Do not return anything, modify nums in-place instead. + """ + + diff --git a/33.search-in-rotated-sorted-array.py b/33.search-in-rotated-sorted-array.py new file mode 100644 index 00000000..1d18f8e3 --- /dev/null +++ b/33.search-in-rotated-sorted-array.py @@ -0,0 +1,91 @@ +# +# @lc app=leetcode id=33 lang=python +# +# [33] Search in Rotated Sorted Array +# +# https://leetcode.com/problems/search-in-rotated-sorted-array/description/ +# +# algorithms +# Medium (32.62%) +# Total Accepted: 373.5K +# Total Submissions: 1.1M +# Testcase Example: '[4,5,6,7,0,1,2]\n0' +# +# Suppose an array sorted in ascending order is rotated at some pivot unknown +# to you beforehand. +# +# (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). +# +# You are given a target value to search. If found in the array return its +# index, otherwise return -1. +# +# You may assume no duplicate exists in the array. +# +# Your algorithm's runtime complexity must be in the order of O(log n). +# +# Example 1: +# +# +# Input: nums = [4,5,6,7,0,1,2], target = 0 +# Output: 4 +# +# +# Example 2: +# +# +# Input: nums = [4,5,6,7,0,1,2], target = 3 +# Output: -1 +# +# +class Solution(object): + def search(self, nums, target): + """ + :type nums: List[int] + :type target: int + :rtype: int + """ + num_len = len(nums) + ids_arr = [] + if num_len == 0: + return -1 + if num_len == 1: + if target == nums[0]: + return 0 + return -1 + front = 0 + rear = 1 + + while rear < num_len and nums[rear] >= nums[front]: + rear += 1 + front += 1 + + if rear < num_len: + part_1 = nums[0:rear] + part_2 = nums[rear:num_len] + nums = part_2 + part_1 + ids_1 = [] + ids_2 = [] + for i in range(rear): + ids_1.append(i) + while rear < num_len: + ids_2.append(rear) + rear += 1 + ids_arr = ids_2 + ids_1 + else: + for i in range(num_len): + ids_arr.append(i) + front = 0 + rear = num_len - 1 + mid = (front+rear)/2 + #search_lst = [] + while front <= rear: + #search_lst.append(mid) + if nums[mid] == target: + return ids_arr[mid] + elif nums[mid] > target: + rear = mid - 1 + else: + front = mid + 1 + mid = (front+rear)/2 + return -1 + diff --git a/34.find-first-and-last-position-of-element-in-sorted-array.py b/34.find-first-and-last-position-of-element-in-sorted-array.py new file mode 100644 index 00000000..bccdeb01 --- /dev/null +++ b/34.find-first-and-last-position-of-element-in-sorted-array.py @@ -0,0 +1,97 @@ +# +# @lc app=leetcode id=34 lang=python +# +# [34] Find First and Last Position of Element in Sorted Array +# +# https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/description/ +# +# algorithms +# Medium (33.01%) +# Total Accepted: 270.3K +# Total Submissions: 818.7K +# Testcase Example: '[5,7,7,8,8,10]\n8' +# +# Given an array of integers nums sorted in ascending order, find the starting +# and ending position of a given target value. +# +# Your algorithm's runtime complexity must be in the order of O(log n). +# +# If the target is not found in the array, return [-1, -1]. +# +# Example 1: +# +# +# Input: nums = [5,7,7,8,8,10], target = 8 +# Output: [3,4] +# +# Example 2: +# +# +# Input: nums = [5,7,7,8,8,10], target = 6 +# Output: [-1,-1] +# +# +''' +class Solution(object): + def searchRange(self, nums, target): + """ + :type nums: List[int] + :type target: int + :rtype: List[int] + """ + res_lst = [] + if nums == []: + return [-1, -1] + if target < nums[0] or target > nums[-1]: + return [-1, -1] + front = 0 + num_len = len(nums) + rear = (num_len - 1)/2 + mid = (rear+front)/2 + while rear >=front: + if nums[mid] == target: + res_lst = [mid] +res_lst + rear = mid - 1 + else: + front = mid + 1 + mid = (front+rear)/2 + rear = num_len - 1 + front = rear/2 + mid = (front+rear)/2 + while rear >= front: + if nums[mid] == target: + res_lst.append(mid) + front = mid + 1 + else: + rear = mid - 1 + mid = (front+rear)/2 + if res_lst == []: + return [-1, -1] + return res_lst +''' +class Solution: + # returns leftmost (or rightmost) index at which `target` should be inserted in sorted + # array `nums` via binary search. + def extreme_insertion_index(self, nums, target, left): + lo = 0 + hi = len(nums) + + while lo < hi: + mid = (lo + hi) // 2 + if nums[mid] > target or (left and target == nums[mid]): + hi = mid + else: + lo = mid+1 + + return lo + + + def searchRange(self, nums, target): + left_idx = self.extreme_insertion_index(nums, target, True) + + # assert that `left_idx` is within the array bounds and that `target` + # is actually in `nums`. + if left_idx == len(nums) or nums[left_idx] != target: + return [-1, -1] + + return [left_idx, self.extreme_insertion_index(nums, target, False)-1] \ No newline at end of file diff --git a/36.valid-sudoku.py b/36.valid-sudoku.py new file mode 100644 index 00000000..dd689df4 --- /dev/null +++ b/36.valid-sudoku.py @@ -0,0 +1,115 @@ +# +# @lc app=leetcode id=36 lang=python +# +# [36] Valid Sudoku +# +# https://leetcode.com/problems/valid-sudoku/description/ +# +# algorithms +# Medium (41.93%) +# Total Accepted: 216.5K +# Total Submissions: 516.5K +# Testcase Example: '[["5","3",".",".","7",".",".",".","."],["6",".",".","1","9","5",".",".","."],[".","9","8",".",".",".",".","6","."],["8",".",".",".","6",".",".",".","3"],["4",".",".","8",".","3",".",".","1"],["7",".",".",".","2",".",".",".","6"],[".","6",".",".",".",".","2","8","."],[".",".",".","4","1","9",".",".","5"],[".",".",".",".","8",".",".","7","9"]]' +# +# Determine if a 9x9 Sudoku board is valid. Only the filled cells need to be +# validated according to the following rules: +# +# +# Each row must contain the digits 1-9 without repetition. +# Each column must contain the digits 1-9 without repetition. +# Each of the 9 3x3 sub-boxes of the grid must contain the digits 1-9 without +# repetition. +# +# +# +# A partially filled sudoku which is valid. +# +# The Sudoku board could be partially filled, where empty cells are filled with +# the character '.'. +# +# Example 1: +# +# +# Input: +# [ +# ⁠ ["5","3",".",".","7",".",".",".","."], +# ⁠ ["6",".",".","1","9","5",".",".","."], +# ⁠ [".","9","8",".",".",".",".","6","."], +# ⁠ ["8",".",".",".","6",".",".",".","3"], +# ⁠ ["4",".",".","8",".","3",".",".","1"], +# ⁠ ["7",".",".",".","2",".",".",".","6"], +# ⁠ [".","6",".",".",".",".","2","8","."], +# ⁠ [".",".",".","4","1","9",".",".","5"], +# ⁠ [".",".",".",".","8",".",".","7","9"] +# ] +# Output: true +# +# +# Example 2: +# +# +# Input: +# [ +# ["8","3",".",".","7",".",".",".","."], +# ["6",".",".","1","9","5",".",".","."], +# [".","9","8",".",".",".",".","6","."], +# ["8",".",".",".","6",".",".",".","3"], +# ["4",".",".","8",".","3",".",".","1"], +# ["7",".",".",".","2",".",".",".","6"], +# [".","6",".",".",".",".","2","8","."], +# [".",".",".","4","1","9",".",".","5"], +# [".",".",".",".","8",".",".","7","9"] +# ] +# Output: false +# Explanation: Same as Example 1, except with the 5 in the top left corner +# being +# ⁠ modified to 8. Since there are two 8's in the top left 3x3 sub-box, it is +# invalid. +# +# +# Note: +# +# +# A Sudoku board (partially filled) could be valid but is not necessarily +# solvable. +# Only the filled cells need to be validated according to the mentioned +# rules. +# The given board contain only digits 1-9 and the character '.'. +# The given board size is always 9x9. +# +# +# +class Solution(object): + def isValidSudoku(self, board): + """ + :type board: List[List[str]] + :rtype: bool + """ + row = len(board) + col = len(board[0]) + for i in range(row): + row_elem = [] + col_elem = [] + sub_mat_elem = [] + for j in range(col): + if board[i][j] != '.': + if board[i][j] not in row_elem: + row_elem.append(board[i][j]) + else: + return False + if board[j][i] != '.': + if board[j][i] not in col_elem: + col_elem.append(board[j][i]) + else: + return False + mat_row = 3*(i/3) + mat_col = 3*(i%3) + if board[mat_row+j/3][mat_col+j%3] != '.': + if board[mat_row+j/3][mat_col+j%3] not in sub_mat_elem: + sub_mat_elem.append(board[mat_row+j/3][mat_col+j%3]) + else: + return False + return True + + + diff --git a/39.combination-sum.py b/39.combination-sum.py new file mode 100644 index 00000000..34f0eff4 --- /dev/null +++ b/39.combination-sum.py @@ -0,0 +1,82 @@ +# +# @lc app=leetcode id=39 lang=python +# +# [39] Combination Sum +# +# https://leetcode.com/problems/combination-sum/description/ +# +# algorithms +# Medium (46.81%) +# Total Accepted: 308.3K +# Total Submissions: 658.6K +# Testcase Example: '[2,3,6,7]\n7' +# +# Given a set of candidate numbers (candidates) (without duplicates) and a +# target number (target), find all unique combinations in candidates where the +# candidate numbers sums to target. +# +# The same repeated number may be chosen from candidates unlimited number of +# times. +# +# Note: +# +# +# All numbers (including target) will be positive integers. +# The solution set must not contain duplicate combinations. +# +# +# Example 1: +# +# +# Input: candidates = [2,3,6,7], target = 7, +# A solution set is: +# [ +# ⁠ [7], +# ⁠ [2,2,3] +# ] +# +# +# Example 2: +# +# +# Input: candidates = [2,3,5], target = 8, +# A solution set is: +# [ +# [2,2,2,2], +# [2,3,3], +# [3,5] +# ] +# +# +# +class Solution(object): + def solver(self, candidates, target, results, sub_res, pos): + if target == 0: + results.append(sub_res) + sub_res = [] + return + if target < 0: + return + pre = -99999 + #tmp_res = list(sub_res) + for i in range(pos, len(candidates)): + if target-candidates[i] < 0: + return + if pre == candidates[i]: + continue + #tmp_res.append(candidates[i]) + self.solver(candidates, + target-candidates[i], + results, sub_res+[candidates[i]], i) + #tmp_res = tmp_res[0:-1] + pre = candidates[i] + def combinationSum(self, candidates, target): + """ + :type candidates: List[int] + :type target: int + :rtype: List[List[int]] + """ + candidates.sort() + res = [] + self.solver(candidates, target, res, [], 0) + return res diff --git a/40.combination-sum-ii.py b/40.combination-sum-ii.py new file mode 100644 index 00000000..ee6b756b --- /dev/null +++ b/40.combination-sum-ii.py @@ -0,0 +1,74 @@ +# +# @lc app=leetcode id=40 lang=python +# +# [40] Combination Sum II +# +# https://leetcode.com/problems/combination-sum-ii/description/ +# +# algorithms +# Medium (40.24%) +# Total Accepted: 202.6K +# Total Submissions: 503.3K +# Testcase Example: '[10,1,2,7,6,1,5]\n8' +# +# Given a collection of candidate numbers (candidates) and a target number +# (target), find all unique combinations in candidates where the candidate +# numbers sums to target. +# +# Each number in candidates may only be used once in the combination. +# +# Note: +# +# +# All numbers (including target) will be positive integers. +# The solution set must not contain duplicate combinations. +# +# +# Example 1: +# +# +# Input: candidates = [10,1,2,7,6,1,5], target = 8, +# A solution set is: +# [ +# ⁠ [1, 7], +# ⁠ [1, 2, 5], +# ⁠ [2, 6], +# ⁠ [1, 1, 6] +# ] +# +# +# Example 2: +# +# +# Input: candidates = [2,5,2,1,2], target = 5, +# A solution set is: +# [ +# [1,2,2], +# [5] +# ] +# +# +# +class Solution(object): + def solver(self, candidates, target, result, tmp_res, pos): + if target == 0: + if tmp_res not in result: + result.append(tmp_res) + return + if target < 0: + return + for i in range(pos, len(candidates)): + if target - candidates[i] < 0: + return + self.solver(candidates, target-candidates[i], + result,tmp_res+[candidates[i]], i+1) + def combinationSum2(self, candidates, target): + """ + :type candidates: List[int] + :type target: int + :rtype: List[List[int]] + """ + candidates.sort() + results = [] + self.solver(candidates, target, results, [], 0) + return results diff --git a/43.multiply-strings.py b/43.multiply-strings.py new file mode 100644 index 00000000..9bc148f1 --- /dev/null +++ b/43.multiply-strings.py @@ -0,0 +1,139 @@ +# +# @lc app=leetcode id=43 lang=python +# +# [43] Multiply Strings +# +# https://leetcode.com/problems/multiply-strings/description/ +# +# algorithms +# Medium (29.99%) +# Total Accepted: 185.2K +# Total Submissions: 617.4K +# Testcase Example: '"2"\n"3"' +# +# Given two non-negative integers num1 and num2 represented as strings, return +# the product of num1 and num2, also represented as a string. +# +# Example 1: +# +# +# Input: num1 = "2", num2 = "3" +# Output: "6" +# +# Example 2: +# +# +# Input: num1 = "123", num2 = "456" +# Output: "56088" +# +# +# Note: +# +# +# The length of both num1 and num2 is < 110. +# Both num1 and num2 contain only digits 0-9. +# Both num1 and num2 do not contain any leading zero, except the number 0 +# itself. +# You must not use any built-in BigInteger library or convert the inputs to +# integer directly. +# +# +# +''' +class Solution(object): + def multiply(self, num1, num2): + """ + :type num1: str + :type num2: str + :rtype: str + """ + num1 = num1[::-1] # Calculate the result from the rear. + num2 = num2[::-1] + if num1 == '0' or num2 == '0': + return '0' + if len(num1) < len(num2): + row_len = len(num1) + 1 + row_num = num1 + col_len = len(num2) + 1 + col_num =num2 + else: + row_len = len(num2) + 1 + row_num = num2 + col_len = len(num1) + 1 + col_num = num1 + num_mat = [] + for row in range(row_len): + num_mat.append([0]*col_len) + adv = 0 + # store the multiply results between each nums in a matrix. + tmp_ad = [] + for row in range(row_len): + if row == row_len - 1: + break + for col in range(col_len): + if col == col_len - 1: + num_mat[row][col] = adv # store the adv at the last column. + adv = 0 + break + mul_res = int(row_num[row]) * int(col_num[col]) + adv + adv = mul_res / 10 + num_mat[row][col] = mul_res % 10 + tmp_ad.append(adv) + res = '' + + for col in range(0, col_len): + row = 0 + col1 = col + tmp_res = 0 + + while row=0: + tmp_res += num_mat[row][col1] + row += 1 + col1 -= 1 + tmp_res = tmp_res + adv + res = str(tmp_res%10) + res + adv = tmp_res / 10 + + row = 1 + while row < row_len: + col = col_len - 1 + row1 = row + tmp_res = 0 + while row10: + tmp_res += num_mat[row1][col] + row1 += 1 + col -= 1 + tmp_res = tmp_res + adv + res = str(tmp_res%10) + res + adv = tmp_res / 10 + row += 1 + while res[0] == '0': + res = res[1:] + if adv != 0: + res = str(adv) + res + return res +''' +class Solution(object): + def multiply(self, num1, num2): + """ + :type num1: str + :type num2: str + :rtype: str + """ + num1 = num1[::-1] # Calculate the result from the rear. + num2 = num2[::-1] + product = [0] * (len(num1)+len(num2)) + pos = 1 + for n1 in num1: + tmp_pos = pos + for n2 in num2: + product[tmp_pos-1] += int(n1)*int(n2) + product[tmp_pos] += product[tmp_pos-1] / 10 + product[tmp_pos-1] %= 10 + tmp_pos += 1 + pos += 1 + product = product[::-1] + while product[0]==0 and len(product)!=1: + product = product[1:] + product = [str(x) for x in product] + return ''.join(product) diff --git a/46.permutations.py b/46.permutations.py new file mode 100644 index 00000000..7b640f8a --- /dev/null +++ b/46.permutations.py @@ -0,0 +1,56 @@ +# +# @lc app=leetcode id=46 lang=python +# +# [46] Permutations +# +# https://leetcode.com/problems/permutations/description/ +# +# algorithms +# Medium (53.51%) +# Total Accepted: 343K +# Total Submissions: 640.8K +# Testcase Example: '[1,2,3]' +# +# Given a collection of distinct integers, return all possible permutations. +# +# Example: +# +# +# Input: [1,2,3] +# Output: +# [ +# ⁠ [1,2,3], +# ⁠ [1,3,2], +# ⁠ [2,1,3], +# ⁠ [2,3,1], +# ⁠ [3,1,2], +# ⁠ [3,2,1] +# ] +# +# +# +class Solution(object): + def solver(self, nums, result, tmp_res): + if len(nums) == 0: + if tmp_res not in result: + result.append(tmp_res) + return + pre = -9999 + for i in range(len(nums)): + if pre == nums[i]: + continue + self.solver(nums[:i]+nums[i+1:], result, tmp_res+[nums[i]]) + #if i > 0: + # self.solver(nums[:i]+nums[i+1:], result,[nums[i]]+tmp_res, length) + + + def permute(self, nums): + """ + :type nums: List[int] + :rtype: List[List[int]] + """ + res = [] + self.solver(nums, res, []) + return res + + diff --git a/47.permutations-ii.py b/47.permutations-ii.py new file mode 100644 index 00000000..c6c64c93 --- /dev/null +++ b/47.permutations-ii.py @@ -0,0 +1,51 @@ +# +# @lc app=leetcode id=47 lang=python +# +# [47] Permutations II +# +# https://leetcode.com/problems/permutations-ii/description/ +# +# algorithms +# Medium (39.22%) +# Total Accepted: 223.1K +# Total Submissions: 568.6K +# Testcase Example: '[1,1,2]' +# +# Given a collection of numbers that might contain duplicates, return all +# possible unique permutations. +# +# Example: +# +# +# Input: [1,1,2] +# Output: +# [ +# ⁠ [1,1,2], +# ⁠ [1,2,1], +# ⁠ [2,1,1] +# ] +# +# +# +class Solution(object): + def solver(self, nums, result, tmp_res): + if len(nums) == 0: + if tmp_res not in result: + result.append(tmp_res) + return + pre = -9999 + for i in range(len(nums)): + if pre == nums[i]: + continue + self.solver(nums[:i]+nums[i+1:], result, tmp_res+[nums[i]]) + pre = nums[i] + + def permuteUnique(self, nums): + """ + :type nums: List[int] + :rtype: List[List[int]] + """ + res = [] + self.solver(nums, res, []) + return res + diff --git a/48.rotate-image.py b/48.rotate-image.py new file mode 100644 index 00000000..42c94717 --- /dev/null +++ b/48.rotate-image.py @@ -0,0 +1,87 @@ +# +# @lc app=leetcode id=48 lang=python +# +# [48] Rotate Image +# +# https://leetcode.com/problems/rotate-image/description/ +# +# algorithms +# Medium (46.92%) +# Total Accepted: 227.9K +# Total Submissions: 485.4K +# Testcase Example: '[[1,2,3],[4,5,6],[7,8,9]]' +# +# You are given an n x n 2D matrix representing an image. +# +# Rotate the image by 90 degrees (clockwise). +# +# Note: +# +# You have to rotate the image in-place, which means you have to modify the +# input 2D matrix directly. DO NOT allocate another 2D matrix and do the +# rotation. +# +# Example 1: +# +# +# Given input matrix = +# [ +# ⁠ [1,2,3], +# ⁠ [4,5,6], +# ⁠ [7,8,9] +# ], +# +# rotate the input matrix in-place such that it becomes: +# [ +# ⁠ [7,4,1], +# ⁠ [8,5,2], +# ⁠ [9,6,3] +# ] +# +# +# Example 2: +# +# +# Given input matrix = +# [ +# ⁠ [ 5, 1, 9,11], +# ⁠ [ 2, 4, 8,10], +# ⁠ [13, 3, 6, 7], +# ⁠ [15,14,12,16] +# ], +# +# rotate the input matrix in-place such that it becomes: +# [ +# ⁠ [15,13, 2, 5], +# ⁠ [14, 3, 4, 1], +# ⁠ [12, 6, 8, 9], +# ⁠ [16, 7,10,11] +# ] +# +# +# +class Solution(object): + def rotate(self, matrix): + """ + :type matrix: List[List[int]] + :rtype: None Do not return anything, modify matrix in-place instead. + """ + + dim = len(matrix) + ''' + for i in range(s_len): + row = i / dim + col = i % dim + if row == col: + continue # ignore the elems on diag. + matrix[row][col], matrix[col][row] = matrix[col][row], matrix[row][col] + ''' + for i in range(dim): + for j in range(i + 1, dim): + matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] + + for row in range(dim): + matrix[row].reverse() + #return matrix + + diff --git a/49.group-anagrams.py b/49.group-anagrams.py new file mode 100644 index 00000000..1f342cff --- /dev/null +++ b/49.group-anagrams.py @@ -0,0 +1,81 @@ +# +# @lc app=leetcode id=49 lang=python +# +# [49] Group Anagrams +# +# https://leetcode.com/problems/group-anagrams/description/ +# +# algorithms +# Medium (44.88%) +# Total Accepted: 300.2K +# Total Submissions: 668.2K +# Testcase Example: '["eat","tea","tan","ate","nat","bat"]' +# +# Given an array of strings, group anagrams together. +# +# Example: +# +# +# Input: ["eat", "tea", "tan", "ate", "nat", "bat"], +# Output: +# [ +# ⁠ ["ate","eat","tea"], +# ⁠ ["nat","tan"], +# ⁠ ["bat"] +# ] +# +# Note: +# +# +# All inputs will be in lowercase. +# The order of your output does not matter. +# +# +# +''' +class Solution(object): + def groupAnagrams(self, strs): + """ + :type strs: List[str] + :rtype: List[List[str]] + """ + sort_strs = [] + res = [] + for s in strs: + tmp = list(s) + tmp.sort() + tmp = ''.join(tmp) + sort_strs.append(tmp) + visited = [] + for i in range(len(strs)): + if sort_strs[i] in visited: + continue + visited.append(sort_strs[i]) + anagram = [strs[i]] + for j in range(i+1, len(strs)): + if sort_strs[j] == sort_strs[i]: + anagram.append(strs[j]) + res.append(anagram) + return res +''' +class Solution(object): + def groupAnagrams(self, strs): + """ + :type strs: List[str] + :rtype: List[List[str]] + """ + # get the counts of each str in strs + sort_strs = [] + tbl = {} + for s in strs: + tmp = sorted(s) + tmp = ''.join(tmp) + sort_strs.append(tmp) + for i, s in enumerate(sort_strs): + if s not in tbl: + tbl[s] = [strs[i]] + else: + tbl[s].append(strs[i]) + res = tbl.values() + return res + diff --git a/5.longest-palindromic-substring.py b/5.longest-palindromic-substring.py new file mode 100644 index 00000000..9d8e7a64 --- /dev/null +++ b/5.longest-palindromic-substring.py @@ -0,0 +1,98 @@ +# +# @lc app=leetcode id=5 lang=python +# +# [5] Longest Palindromic Substring +# +# https://leetcode.com/problems/longest-palindromic-substring/description/ +# +# algorithms +# Medium (26.52%) +# Total Accepted: 480.1K +# Total Submissions: 1.8M +# Testcase Example: '"babad"' +# +# Given a string s, find the longest palindromic substring in s. You may assume +# that the maximum length of s is 1000. +# +# Example 1: +# +# +# Input: "babad" +# Output: "bab" +# Note: "aba" is also a valid answer. +# +# +# Example 2: +# +# +# Input: "cbbd" +# Output: "bb" +# +# +# + +class Solution(object): + def longestPalindrome(self, s): + """ + :type s: str + :rtype: str + """ + s_len = len(s) + max_s = '' + rev_s = s[::-1] + if rev_s == s: + return s + #s_mat = [] + pali_mat_1 = [] + #pali_mat_2 = [] + max_sub_len = 0 + # Create the LCS matrix + for i in range(s_len+1): + #arr_col = [] + arr_col_p = [] + for j in range(s_len+1): + #arr_col.append(0) + arr_col_p.append('') + #s_mat.append(arr_col) + pali_mat_1.append(arr_col_p) + #pali_mat_2.append(arr_col) + for j in range(s_len+1): + if i>0 and j>0: + if s[j-1] == rev_s[i-1]: + #s_mat[i][j] = s_mat[i-1][j-1] + 1 + pali_mat_1[i][j] = pali_mat_1[i-1][j-1] +\ + pali_mat_1[i][j] + rev_s[i-1] + sub_s = pali_mat_1[i][j] + pali_mat_1[i-1][j-1] = None + rev_sub_s = sub_s[::-1] + sub_s_len = len(sub_s) + if rev_sub_s == sub_s: + #pali_mat_2[i][j] = 1 + if sub_s_len > max_sub_len: + max_sub_len = sub_s_len + max_s = sub_s + + return max_s +''' + + +class Solution(object): + def longestPalindrome(self, s): + """ + :type s: str + :rtype: str + """ + s_len = len(s) + max_s = '' + rev_s = s[::-1] + if rev_s == s: + return s + max_s = '' + for i in range(s_len): + j = i + 1 + while j <= s_len and len(s[i:j])<= len(s[i:]): + if s[i:j] == s[i:j][::-1] and len(s[i:j]) >= len(max_s): + max_s = s[i:j] + j = j + 1 + return max_s +''' diff --git a/50.pow-x-n.py b/50.pow-x-n.py new file mode 100644 index 00000000..3d731356 --- /dev/null +++ b/50.pow-x-n.py @@ -0,0 +1,61 @@ +# +# @lc app=leetcode id=50 lang=python +# +# [50] Pow(x, n) +# +# https://leetcode.com/problems/powx-n/description/ +# +# algorithms +# Medium (27.56%) +# Total Accepted: 293.2K +# Total Submissions: 1.1M +# Testcase Example: '2.00000\n10' +# +# Implement pow(x, n), which calculates x raised to the power n (x^n). +# +# Example 1: +# +# +# Input: 2.00000, 10 +# Output: 1024.00000 +# +# +# Example 2: +# +# +# Input: 2.10000, 3 +# Output: 9.26100 +# +# +# Example 3: +# +# +# Input: 2.00000, -2 +# Output: 0.25000 +# Explanation: 2^-2 = 1/2^2 = 1/4 = 0.25 +# +# +# Note: +# +# +# -100.0 < x < 100.0 +# n is a 32-bit signed integer, within the range [−2^31, 2^31 − 1] +# +# +# +class Solution: + def myPow(self, x, n): + #fast power + if n == 0: + return 1 + if n == 1: + return x + if n == -1: + return 1/x + + q,r = divmod(n,2) + + half = self.myPow(x, q) + reminder = self.myPow(x,r) + + return half*half*reminder diff --git a/53.maximum-subarray.py b/53.maximum-subarray.py new file mode 100644 index 00000000..d4eed688 --- /dev/null +++ b/53.maximum-subarray.py @@ -0,0 +1,107 @@ +# +# @lc app=leetcode id=53 lang=python +# +# [53] Maximum Subarray +# +# https://leetcode.com/problems/maximum-subarray/description/ +# +# algorithms +# Easy (42.84%) +# Total Accepted: 471.5K +# Total Submissions: 1.1M +# Testcase Example: '[-2,1,-3,4,-1,2,1,-5,4]' +# +# Given an integer array nums, find the contiguous subarray (containing at +# least one number) which has the largest sum and return its sum. +# +# Example: +# +# +# Input: [-2,1,-3,4,-1,2,1,-5,4], +# Output: 6 +# Explanation: [4,-1,2,1] has the largest sum = 6. +# +# +# Follow up: +# +# If you have figured out the O(n) solution, try coding another solution using +# the divide and conquer approach, which is more subtle. +# +# +''' +class Solution(object): + max_sum = 0 + max_lst = [] + sum_lst = [] + visited = [] + def solver(self, nums, head, tail, sum_res): + if head > tail or head >= len(nums): + return + if self.visited[head] != -1 and self.visited[tail] != -1: + return + if sum_res >= self.max_sum: + self.sum_lst.append + self.max_sum = sum_res + self.max_lst = nums[head:tail+1] + self.solver(nums, head+1, tail, sum_res-nums[head]) + self.solver(nums, head, tail-1, sum_res-nums[tail]) + self.visited[head] = 1 + self.visited[tail] = 1 + + def maxSubArray(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + tail = len(nums) - 1 + head = 0 + self.max_lst = nums + self.max_sum = 0 + for n in nums: + self.max_sum = self.max_sum + n + self.visited.append(-1) + self.solver(nums, head, tail, self.max_sum) + return self.max_sum + +class Solution(object): + + def maxSubArray(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + max_sum = 0 + for n in nums: + max_sum = max_sum + n + rear = len(nums) - 1 + head = 0 + c = [max_sum] + p = [max_sum] + while head < rear: + p_sum = p[-1] + f_res = p_sum - nums[rear] + r_res = p_sum - nums[head] + if f_res > r_res: + rear -= 1 + p.append(f_res) + c.append(max(max_sum, f_res)) + else: + head += 1 + p.append(r_res) + c.append(max(max_sum, r_res)) + return p +''' + +class Solution(object): + + def maxSubArray(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + max_sum = nums[0] + cur_res = nums[0] + for i in range(1, len(nums)): + cur_res = max(cur_res+nums[i], nums[i]) + max_sum = max(cur_res, max_sum) + return max_sum diff --git a/54.spiral-matrix.py b/54.spiral-matrix.py new file mode 100644 index 00000000..183e79be --- /dev/null +++ b/54.spiral-matrix.py @@ -0,0 +1,94 @@ +# +# @lc app=leetcode id=54 lang=python +# +# [54] Spiral Matrix +# +# https://leetcode.com/problems/spiral-matrix/description/ +# +# algorithms +# Medium (29.66%) +# Total Accepted: 212K +# Total Submissions: 714.3K +# Testcase Example: '[[1,2,3],[4,5,6],[7,8,9]]' +# +# Given a matrix of m x n elements (m rows, n columns), return all elements of +# the matrix in spiral order. +# +# Example 1: +# +# +# Input: +# [ +# ⁠[ 1, 2, 3 ], +# ⁠[ 4, 5, 6 ], +# ⁠[ 7, 8, 9 ] +# ] +# Output: [1,2,3,6,9,8,7,4,5] +# +# +# Example 2: +# +# Input: +# [ +# ⁠ [1, 2, 3, 4], +# ⁠ [5, 6, 7, 8], +# ⁠ [9,10,11,12] +# ] +# Output: [1,2,3,4,8,12,11,10,9,5,6,7] +# +# +class Solution(object): + ''' + def spiralOrder(self, matrix): + ret = [] + while matrix: + ret += matrix.pop(0) + if matrix and matrix[0]: + for row in matrix: + ret.append(row.pop()) + if matrix: + ret += matrix.pop()[::-1] + if matrix and matrix[0]: + for row in matrix[::-1]: + ret.append(row.pop(0)) + return ret + ''' + def spiralOrder(self, matrix): + """ + :type matrix: List[List[int]] + :rtype: List[int] + """ + if matrix == []: + return [] + row_nums = len(matrix) + col_nums = len(matrix[0]) + nums = row_nums*col_nums + visit_mat = [] + for row in range(row_nums): + col_arr = [0]*col_nums + visit_mat.append(col_arr) + row = 0 + col = 0 + di = 0 + dir_r = [0,1,0,-1] # move up and down + dir_c = [1,0,-1,0] # move right and left + result = [] # save the result + for i in range(nums): + result.append(matrix[row][col]) + visit_mat[row][col] = 1 # note the visited elem + # clock-wise + n_row = row + dir_r[di] + n_col = col + dir_c[di] + if 0<=n_row m: + return False + m = max(m, i+n) + return True +''' +class Solution(object): + def canJump(self, nums): + """ + :type nums: List[int] + :rtype: bool + """ + goal = len(nums)-1 + for i in range(len(nums))[::-1]: + if i + nums[i] >= goal: + goal = i + return not goal diff --git a/56.merge-intervals.py b/56.merge-intervals.py new file mode 100644 index 00000000..d3c3a9d4 --- /dev/null +++ b/56.merge-intervals.py @@ -0,0 +1,57 @@ +# +# @lc app=leetcode id=56 lang=python +# +# [56] Merge Intervals +# +# https://leetcode.com/problems/merge-intervals/description/ +# +# algorithms +# Medium (34.87%) +# Total Accepted: 314K +# Total Submissions: 897.8K +# Testcase Example: '[[1,3],[2,6],[8,10],[15,18]]' +# +# Given a collection of intervals, merge all overlapping intervals. +# +# Example 1: +# +# +# Input: [[1,3],[2,6],[8,10],[15,18]] +# Output: [[1,6],[8,10],[15,18]] +# Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into +# [1,6]. +# +# +# Example 2: +# +# +# Input: [[1,4],[4,5]] +# Output: [[1,5]] +# Explanation: Intervals [1,4] and [4,5] are considered overlapping. +# +# +# Definition for an interval. +# class Interval(object): +# def __init__(self, s=0, e=0): +# self.start = s +# self.end = e + +class Solution(object): + def merge(self, intervals): + """ + :type intervals: List[Interval] + :rtype: List[Interval] + """ + intervals.sort(key=lambda x: x.start) + new_intervals = [] + for interval in intervals: + if new_intervals==[] or new_intervals[-1].end 0: + if header_1-1+tmp_dim >= s_len: + tmp_dim = tmp_dim - 1 + continue + arr_col_2[diag_nums-tmp_dim+1] = s[header_1+tmp_dim-1] + tmp_dim = tmp_dim - 1 + #arr_col_2 = arr_col_2[::-1] + + for i in range(numRows): + if header+i >=s_len: + break + arr_col_1[i] = s[header+i] + + str_mat.append(arr_col_1) + str_mat.append(arr_col_2) + header = header_1 + diag_nums + header_1 = header + numRows + res_str = '' + for col in range(len(str_mat[0])): + for row in range(len(str_mat)): + res_str = res_str + str_mat[row][col] + + return res_str + diff --git a/60.permutation-sequence.py b/60.permutation-sequence.py new file mode 100644 index 00000000..20b6b96a --- /dev/null +++ b/60.permutation-sequence.py @@ -0,0 +1,115 @@ +# +# @lc app=leetcode id=60 lang=python +# +# [60] Permutation Sequence +# +# https://leetcode.com/problems/permutation-sequence/description/ +# +# algorithms +# Medium (32.33%) +# Total Accepted: 129.9K +# Total Submissions: 401.6K +# Testcase Example: '3\n3' +# +# The set [1,2,3,...,n] contains a total of n! unique permutations. +# +# By listing and labeling all of the permutations in order, we get the +# following sequence for n = 3: +# +# +# "123" +# "132" +# "213" +# "231" +# "312" +# "321" +# +# +# Given n and k, return the k^th permutation sequence. +# +# Note: +# +# +# Given n will be between 1 and 9 inclusive. +# Given k will be between 1 and n! inclusive. +# +# +# Example 1: +# +# +# Input: n = 3, k = 3 +# Output: "213" +# +# +# Example 2: +# +# +# Input: n = 4, k = 9 +# Output: "2314" +# +# +# +''' +class Solution(object): + def solver(self, nums, size, k, seq_set, seq, cnt,sw): + if len(seq) == size: + cnt[0] += 1 + if cnt[0] == k: + seq_set.append(seq) + sw[0] = False + return + if sw[0] == True: + for i in range(len(nums)): + + res = self.solver(nums[:i]+nums[i+1:], size, k, seq_set, seq+nums[i], cnt, sw) + if res is True: + break + def getPermutation(self, n, k): + """ + :type n: int + :type k: int + :rtype: str + """ + nums = '' + # create the first permutation. + for s in range(1,n+1): + nums += str(s) + res_set = [] + cnt = [0] + sw = [True] + #DFS + self.solver(nums,n,k, res_set,'',cnt,sw) + return res_set[0] +''' +class Solution(object): + def get_factorial(self, n): + res = 1 + if n == 0: + return 1 # 0! = 1 + for i in range(1, n+1): + res *= i + return res + def getPermutation(self, n, k): + """ + Reference: + https://leetcode.com/problems/permutation-sequence/discuss/22507/%22Explain-like-I'm-five%22-Java-Solution-in-O(n) + :type n: int + :type k: int + :rtype: str + """ + res = '' + k -= 1 + cnt = 1 + init_set = [] + for i in range(1,n+1): + init_set.append(str(i)) + while len(res) != n: + factorial = self.get_factorial(n-cnt) + ids = k / factorial + res += init_set[ids] + init_set.pop(ids) + k = k - ids * factorial + cnt += 1 + return res + + diff --git a/61.rotate-list.py b/61.rotate-list.py new file mode 100644 index 00000000..4cfe3cca --- /dev/null +++ b/61.rotate-list.py @@ -0,0 +1,114 @@ +# +# @lc app=leetcode id=61 lang=python +# +# [61] Rotate List +# +# https://leetcode.com/problems/rotate-list/description/ +# +# algorithms +# Medium (26.53%) +# Total Accepted: 180.6K +# Total Submissions: 678.2K +# Testcase Example: '[1,2,3,4,5]\n2' +# +# Given a linked list, rotate the list to the right by k places, where k is +# non-negative. +# +# Example 1: +# +# +# Input: 1->2->3->4->5->NULL, k = 2 +# Output: 4->5->1->2->3->NULL +# Explanation: +# rotate 1 steps to the right: 5->1->2->3->4->NULL +# rotate 2 steps to the right: 4->5->1->2->3->NULL +# +# +# Example 2: +# +# +# Input: 0->1->2->NULL, k = 4 +# Output: 2->0->1->NULL +# Explanation: +# rotate 1 steps to the right: 2->0->1->NULL +# rotate 2 steps to the right: 1->2->0->NULL +# rotate 3 steps to the right: 0->1->2->NULL +# rotate 4 steps to the right: 2->0->1->NULL +# +# +# Definition for singly-linked list. +# class ListNode(object): +# def __init__(self, x): +# self.val = x +# self.next = None +''' +class Solution(object): + + def rotateRight(self, head, k): + """ + :type head: ListNode + :type k: int + :rtype: ListNode + """ + if k == 0: + return head + if head == None: + return head + val_set = [] + head_node = ListNode(None) + head_node.next = head + cur_node = head + while cur_node != None: + val_set.append(cur_node.val) + cur_node = cur_node.next + k = k % len(val_set) + val_set = val_set[::-1][0:k][::-1] + val_set[0:len(val_set)-k] + cur_node = head_node.next + cnt = 0 + while cur_node != None: + cur_node.val = val_set[cnt] + cnt = cnt + 1 + cur_node = cur_node.next + head_node = head_node.next + return head_node +''' +class Solution(object): + + def rotateRight(self, head, k): + """ + :type head: ListNode + :type k: int + :rtype: ListNode + """ + if k == 0: + return head + if head == None or head.next==None: + return head + val_set = [] + head_node = ListNode(None) + head_node.next = head + lst_len = 0 + while head != None: + lst_len = lst_len + 1 + head = head.next + k = k % lst_len + if k == 0: + head_node = head_node.next + return head_node + slow_node = head_node.next + fast_node = head_node.next + tmp_k = [k][0] + while tmp_k > 0: + fast_node = fast_node.next + tmp_k = tmp_k - 1 + while fast_node.next != None: + fast_node = fast_node.next + slow_node = slow_node.next + + fast_node.next = head_node.next + head_node.next = slow_node.next + slow_node.next = None + head_node = head_node.next + return head_node + + diff --git a/62.unique-paths.py b/62.unique-paths.py new file mode 100644 index 00000000..c4030c9c --- /dev/null +++ b/62.unique-paths.py @@ -0,0 +1,70 @@ +# +# @lc app=leetcode id=62 lang=python +# +# [62] Unique Paths +# +# https://leetcode.com/problems/unique-paths/description/ +# +# algorithms +# Medium (46.45%) +# Total Accepted: 265.2K +# Total Submissions: 568.9K +# Testcase Example: '3\n2' +# +# A robot is located at the top-left corner of a m x n grid (marked 'Start' in +# the diagram below). +# +# The robot can only move either down or right at any point in time. The robot +# is trying to reach the bottom-right corner of the grid (marked 'Finish' in +# the diagram below). +# +# How many possible unique paths are there? +# +# +# Above is a 7 x 3 grid. How many possible unique paths are there? +# +# Note: m and n will be at most 100. +# +# Example 1: +# +# +# Input: m = 3, n = 2 +# Output: 3 +# Explanation: +# From the top-left corner, there are a total of 3 ways to reach the +# bottom-right corner: +# 1. Right -> Right -> Down +# 2. Right -> Down -> Right +# 3. Down -> Right -> Right +# +# +# Example 2: +# +# +# Input: m = 7, n = 3 +# Output: 28 +# +# +class Solution(object): + def uniquePaths(self, m, n): + """ + :type m: int + :type n: int + :rtype: int + """ + #if m== 1 or n == 1: + # return 1 + matrix = [] + for i in range(m): + matrix.append([0]*n) + for i in range(0, m): + matrix[i][0] = 1 + for i in range(1, n): + matrix[0][i] = 1 + for i in range(1, m): + for j in range(1, n): + matrix[i][j] = matrix[i-1][j] + matrix[i][j-1] + return matrix[-1][-1] + + + diff --git a/63.unique-paths-ii.py b/63.unique-paths-ii.py new file mode 100644 index 00000000..551f0907 --- /dev/null +++ b/63.unique-paths-ii.py @@ -0,0 +1,81 @@ +# +# @lc app=leetcode id=63 lang=python +# +# [63] Unique Paths II +# +# https://leetcode.com/problems/unique-paths-ii/description/ +# +# algorithms +# Medium (33.22%) +# Total Accepted: 186.6K +# Total Submissions: 561.5K +# Testcase Example: '[[0,0,0],[0,1,0],[0,0,0]]' +# +# A robot is located at the top-left corner of a m x n grid (marked 'Start' in +# the diagram below). +# +# The robot can only move either down or right at any point in time. The robot +# is trying to reach the bottom-right corner of the grid (marked 'Finish' in +# the diagram below). +# +# Now consider if some obstacles are added to the grids. How many unique paths +# would there be? +# +# +# +# An obstacle and empty space is marked as 1 and 0 respectively in the grid. +# +# Note: m and n will be at most 100. +# +# Example 1: +# +# +# Input: +# [ +# [0,0,0], +# [0,1,0], +# [0,0,0] +# ] +# Output: 2 +# Explanation: +# There is one obstacle in the middle of the 3x3 grid above. +# There are two ways to reach the bottom-right corner: +# 1. Right -> Right -> Down -> Down +# 2. Down -> Down -> Right -> Right +# +# +# +class Solution(object): + def uniquePathsWithObstacles(self, obstacleGrid): + """ + :type obstacleGrid: List[List[int]] + :rtype: int + """ + row = len(obstacleGrid) + col = len(obstacleGrid[0]) + obstacleGrid[0][0] = 1 - obstacleGrid[0][0] + + + for i in range(1, row): + if obstacleGrid[i][0] == 1: + obstacleGrid[i][0] = 0 # tag the obstacle to 0 + continue + obstacleGrid[i][0] = obstacleGrid[i][0] + obstacleGrid[i-1][0] + + + for i in range(1, col): + if obstacleGrid[0][i] == 1: + obstacleGrid[0][i] = 0 # tag the obstacle to 0 + continue + obstacleGrid[0][i] = obstacleGrid[0][i] + obstacleGrid[0][i-1] + + for i in range(1, row): + for j in range(1, col): + if obstacleGrid[i][j] == 1: + obstacleGrid[i][j] = 0 # tag the obstacle to 0 + continue + obstacleGrid[i][j] = obstacleGrid[i-1][j] + obstacleGrid[i][j-1] + return obstacleGrid[-1][-1] + + + diff --git a/64.minimum-path-sum.py b/64.minimum-path-sum.py new file mode 100644 index 00000000..f598ae31 --- /dev/null +++ b/64.minimum-path-sum.py @@ -0,0 +1,83 @@ +# +# @lc app=leetcode id=64 lang=python +# +# [64] Minimum Path Sum +# +# https://leetcode.com/problems/minimum-path-sum/description/ +# +# algorithms +# Medium (45.62%) +# Total Accepted: 213.4K +# Total Submissions: 466K +# Testcase Example: '[[1,3,1],[1,5,1],[4,2,1]]' +# +# Given a m x n grid filled with non-negative numbers, find a path from top +# left to bottom right which minimizes the sum of all numbers along its path. +# +# Note: You can only move either down or right at any point in time. +# +# Example: +# +# +# Input: +# [ +# [1,3,1], +# ⁠ [1,5,1], +# ⁠ [4,2,1] +# ] +# Output: 7 +# Explanation: Because the path 1→3→1→1→1 minimizes the sum. +# +# +# +''' +class Solution(object): + #val_lst = [] + def dfs(self, grid, path_val, min_val, row, col): + + if row == len(grid) or col == len(grid[0]) or path_val > min_val[0]: + return + + if row == len(grid)-1 and col == len(grid[0])-1: + min_val[0] = min(path_val+grid[row][col], min_val[0]) + #self.val_lst.append(path_val+grid[row][col]) + return + + path_val = path_val + grid[row][col] + self.dfs(grid, path_val, min_val, row+1, col) + self.dfs(grid, path_val, min_val, row, col+1) + def minPathSum(self, grid): + """ + :type grid: List[List[int]] + :rtype: int + """ + path_val = 0 + row = len(grid) + col = len(grid[0]) + min_val = [999999] + self.dfs(grid, path_val, min_val, 0, 0) + return min_val[0] +''' +class Solution(object): + #val_lst = [] + + def minPathSum(self, grid): + """ + :type grid: List[List[int]] + :rtype: int + """ + path_val = 0 + row = len(grid) + col = len(grid[0]) + dp = [[0]*col for _ in range(row)] + dp[0][0] = grid[0][0] + # first rows' path + for i in range(1, col): + dp[0][i] = dp[0][i-1] + grid[0][i] + for i in range(1, row): + dp[i][0] = dp[i-1][0] + grid[i][0] + for i in range(1, row): + for j in range(1, col): + dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + grid[i][j] + return dp[-1][-1] + diff --git a/71.simplify-path.py b/71.simplify-path.py new file mode 100644 index 00000000..f0fe7dd9 --- /dev/null +++ b/71.simplify-path.py @@ -0,0 +1,131 @@ +# +# @lc app=leetcode id=71 lang=python +# +# [71] Simplify Path +# +# https://leetcode.com/problems/simplify-path/description/ +# +# algorithms +# Medium (28.16%) +# Total Accepted: 143K +# Total Submissions: 506.2K +# Testcase Example: '"/home/"' +# +# Given an absolute path for a file (Unix-style), simplify it. Or in other +# words, convert it to the canonical path. +# +# In a UNIX-style file system, a period . refers to the current directory. +# Furthermore, a double period .. moves the directory up a level. For more +# information, see: Absolute path vs relative path in Linux/Unix +# +# Note that the returned canonical path must always begin with a slash /, and +# there must be only a single slash / between two directory names. The last +# directory name (if it exists) must not end with a trailing /. Also, the +# canonical path must be the shortest string representing the absolute +# path. +# +# +# +# Example 1: +# +# +# Input: "/home/" +# Output: "/home" +# Explanation: Note that there is no trailing slash after the last directory +# name. +# +# +# Example 2: +# +# +# Input: "/../" +# Output: "/" +# Explanation: Going one level up from the root directory is a no-op, as the +# root level is the highest level you can go. +# +# +# Example 3: +# +# +# Input: "/home//foo/" +# Output: "/home/foo" +# Explanation: In the canonical path, multiple consecutive slashes are replaced +# by a single one. +# +# +# Example 4: +# +# +# Input: "/a/./b/../../c/" +# Output: "/c" +# +# +# Example 5: +# +# +# Input: "/a/../../b/../c//.//" +# Output: "/c" +# +# +# Example 6: +# +# +# Input: "/a//b////c/d//././/.." +# Output: "/a/b/c" +# +# +# +class Solution(object): + ''' + def simplifyPath(self, path): + """ + :type path: str + :rtype: str + """ + # "/a//b////c/d//././/.." to [a,b,c,d,.,.,..] + path_list = [] + content = '' + for c in path: + if c == '/': + if content != '': + path_list.append(content) + content = '' + else: + content = content + c + if content != '': + path_list.append(content) + new_path_list = [] + for c in path_list: + if c == '..': + if new_path_list != []: + new_path_list = new_path_list[0:-1] + elif c == '.': + continue + else: + new_path_list.append(c) + if new_path_list == []: + return '/' + res_path = '' + for item in new_path_list: + res_path = res_path + '/'+ item + return res_path + ''' + def simplifyPath(self, path): + path_list = path.split('/') + res_path = [] + for item in path_list: + if item in ('','.'): + continue + elif item == '..': + if res_path != []: + res_path.pop() + else: + res_path.append(item) + return '/'+'/'.join(res_path) + + + + + + + diff --git a/73.set-matrix-zeroes.py b/73.set-matrix-zeroes.py new file mode 100644 index 00000000..dfe1a0b6 --- /dev/null +++ b/73.set-matrix-zeroes.py @@ -0,0 +1,68 @@ +# +# @lc app=leetcode id=73 lang=python +# +# [73] Set Matrix Zeroes +# +# https://leetcode.com/problems/set-matrix-zeroes/description/ +# +# algorithms +# Medium (38.99%) +# Total Accepted: 194.1K +# Total Submissions: 496.2K +# Testcase Example: '[[1,1,1],[1,0,1],[1,1,1]]' +# +# Given a m x n matrix, if an element is 0, set its entire row and column to 0. +# Do it in-place. +# +# Example 1: +# +# +# Input: +# [ +# [1,1,1], +# [1,0,1], +# [1,1,1] +# ] +# Output: +# [ +# [1,0,1], +# [0,0,0], +# [1,0,1] +# ] +# +# +# Example 2: +# +# +# Input: +# [ +# [0,1,2,0], +# [3,4,5,2], +# [1,3,1,5] +# ] +# Output: +# [ +# [0,0,0,0], +# [0,4,5,0], +# [0,3,1,0] +# ] +# +# +# Follow up: +# +# +# A straight forward solution using O(mn) space is probably a bad idea. +# A simple improvement uses O(m + n) space, but still not the best +# solution. +# Could you devise a constant space solution? +# +# +# +class Solution(object): + def setZeroes(self, matrix): + """ + :type matrix: List[List[int]] + :rtype: None Do not return anything, modify matrix in-place instead. + """ + + diff --git a/74.search-a-2-d-matrix.py b/74.search-a-2-d-matrix.py new file mode 100644 index 00000000..7d971246 --- /dev/null +++ b/74.search-a-2-d-matrix.py @@ -0,0 +1,102 @@ +# +# @lc app=leetcode id=74 lang=python +# +# [74] Search a 2D Matrix +# +# https://leetcode.com/problems/search-a-2d-matrix/description/ +# +# algorithms +# Medium (34.68%) +# Total Accepted: 210.6K +# Total Submissions: 606.9K +# Testcase Example: '[[1,3,5,7],[10,11,16,20],[23,30,34,50]]\n3' +# +# Write an efficient algorithm that searches for a value in an m x n matrix. +# This matrix has the following properties: +# +# +# Integers in each row are sorted from left to right. +# The first integer of each row is greater than the last integer of the +# previous row. +# +# +# Example 1: +# +# +# Input: +# matrix = [ +# ⁠ [1, 3, 5, 7], +# ⁠ [10, 11, 16, 20], +# ⁠ [23, 30, 34, 50] +# ] +# target = 3 +# Output: true +# +# +# Example 2: +# +# +# Input: +# matrix = [ +# ⁠ [1, 3, 5, 7], +# ⁠ [10, 11, 16, 20], +# ⁠ [23, 30, 34, 50] +# ] +# target = 13 +# Output: false +# +# +class Solution(object): + ''' + def searchMatrix(self, matrix, target): + if not matrix or target is None: + return False + + rows, cols = len(matrix), len(matrix[0]) + low, high = 0, rows * cols - 1 + + while low <= high: + mid = (low + high) / 2 + num = matrix[mid / cols][mid % cols] + + if num == target: + return True + elif num < target: + low = mid + 1 + else: + high = mid - 1 + + return False + ''' + def searchMatrix(self, matrix, target): + """ + :type matrix: List[List[int]] + :type target: int + :rtype: bool + """ + if matrix == []: + return False + row = len(matrix) + col = len(matrix[0]) + loc_row = 0 + loc_col = 0 + if matrix[0] == [] or target < matrix[0][0] or target > matrix[-1][-1]: + return False + + for i, lst in enumerate(matrix): + if lst == []: + return False + if target>=matrix[i][0] and target<=matrix[i][-1]: + front = 0 + rear = col + while front <= rear: + mid = (front+rear)/2 + if target == matrix[i][mid]: + return True + if target < matrix[i][mid]: + rear = mid - 1 + elif target > matrix[i][mid]: + front = mid + 1 + + return False + diff --git a/75.sort-colors.py b/75.sort-colors.py new file mode 100644 index 00000000..c2752673 --- /dev/null +++ b/75.sort-colors.py @@ -0,0 +1,74 @@ +# +# @lc app=leetcode id=75 lang=python +# +# [75] Sort Colors +# +# https://leetcode.com/problems/sort-colors/description/ +# +# algorithms +# Medium (41.37%) +# Total Accepted: 297.5K +# Total Submissions: 716.9K +# Testcase Example: '[2,0,2,1,1,0]' +# +# Given an array with n objects colored red, white or blue, sort them in-place +# so that objects of the same color are adjacent, with the colors in the order +# red, white and blue. +# +# Here, we will use the integers 0, 1, and 2 to represent the color red, white, +# and blue respectively. +# +# Note: You are not suppose to use the library's sort function for this +# problem. +# +# Example: +# +# +# Input: [2,0,2,1,1,0] +# Output: [0,0,1,1,2,2] +# +# Follow up: +# +# +# A rather straight forward solution is a two-pass algorithm using counting +# sort. +# First, iterate the array counting number of 0's, 1's, and 2's, then overwrite +# array with total number of 0's, then 1's and followed by 2's. +# Could you come up with a one-pass algorithm using only constant space? +# +# +# +class Solution(object): + ''' + def sortColors(self, nums): + """ + :type nums: List[int] + :rtype: None Do not return anything, modify nums in-place instead. + """ + for i in range(len(nums)): + insert_pos = i + min_num = nums[i] + for j in range(i+1, len(nums)): + if nums[j] < min_num: + insert_pos = j + min_num = nums[j] + nums[i], nums[insert_pos] = min_num, nums[i] + ''' + def sortColors(self, nums): + """ + :type nums: List[int] + :rtype: None Do not return anything, modify nums in-place instead. + """ + front, rear = 0, len(nums)-1 + + for i in range(len(nums)): + if nums[i] == 0: + nums[i], nums[front] = nums[front], nums[i] + front = front + 1 + elif nums[i] == 2: + nums[i], nums[rear] = nums[rear], nums[i] + rear = rear - 1 + i = i - 1 + + + diff --git a/77.combinations.py b/77.combinations.py new file mode 100644 index 00000000..fff48cf0 --- /dev/null +++ b/77.combinations.py @@ -0,0 +1,61 @@ +# +# @lc app=leetcode id=77 lang=python +# +# [77] Combinations +# +# https://leetcode.com/problems/combinations/description/ +# +# algorithms +# Medium (46.10%) +# Total Accepted: 189.1K +# Total Submissions: 408.1K +# Testcase Example: '4\n2' +# +# Given two integers n and k, return all possible combinations of k numbers out +# of 1 ... n. +# +# Example: +# +# +# Input: n = 4, k = 2 +# Output: +# [ +# ⁠ [2,4], +# ⁠ [3,4], +# ⁠ [2,3], +# ⁠ [1,2], +# ⁠ [1,3], +# ⁠ [1,4], +# ] +# +# +# +class Solution(object): + def solver(self, nums, res, item, k): + if k == 0: + res.append(item) + return + for i in range(len(nums)): + if i == 0: + self.solver(nums[1:], res, item+[nums[i]], k-1) # if len(nums) == 1, then nums[1:] == [] + else: + self.solver(nums[i+1:], res, item+[nums[i]], k-1) + def solver_2(self, nums, index, res, item, k): + if k == 0: + res.append(item) + for i in range(index, len(nums)): + self.solver_2(nums, i+1, res, item+[nums[i]], k-1) + def combine(self, n, k): + """ + :type n: int + :type k: int + :rtype: List[List[int]] + """ + nums = list(range(1, n+1)) + res = [] + item = [] + #self.solver(nums, res, item, k) + self.solver_2(nums, 0, res, item, k) + return res + + diff --git a/78.subsets.py b/78.subsets.py new file mode 100644 index 00000000..15834176 --- /dev/null +++ b/78.subsets.py @@ -0,0 +1,54 @@ +# +# @lc app=leetcode id=78 lang=python +# +# [78] Subsets +# +# https://leetcode.com/problems/subsets/description/ +# +# algorithms +# Medium (51.09%) +# Total Accepted: 338.9K +# Total Submissions: 659K +# Testcase Example: '[1,2,3]' +# +# Given a set of distinct integers, nums, return all possible subsets (the +# power set). +# +# Note: The solution set must not contain duplicate subsets. +# +# Example: +# +# +# Input: nums = [1,2,3] +# Output: +# [ +# ⁠ [3], +# [1], +# [2], +# [1,2,3], +# [1,3], +# [2,3], +# [1,2], +# [] +# ] +# +# +class Solution(object): + def solver(self, nums, index, res, item, k): + #if item not in res: + res.append(item) + if k == 0: + return + for i in range(index, len(nums)): + self.solver(nums, i+1, res, item+[nums[i]], k-1) + def subsets(self, nums): + """ + :type nums: List[int] + :rtype: List[List[int]] + """ + res = [] + self.solver(nums, 0, res, [], len(nums)) + return res + + + diff --git a/79.word-search.py b/79.word-search.py new file mode 100644 index 00000000..24c70044 --- /dev/null +++ b/79.word-search.py @@ -0,0 +1,65 @@ +# +# @lc app=leetcode id=79 lang=python +# +# [79] Word Search +# +# https://leetcode.com/problems/word-search/description/ +# +# algorithms +# Medium (30.58%) +# Total Accepted: 258.5K +# Total Submissions: 845.3K +# Testcase Example: '[["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]]\n"ABCCED"' +# +# Given a 2D board and a word, find if the word exists in the grid. +# +# The word can be constructed from letters of sequentially adjacent cell, where +# "adjacent" cells are those horizontally or vertically neighboring. The same +# letter cell may not be used more than once. +# +# Example: +# +# +# board = +# [ +# ⁠ ['A','B','C','E'], +# ⁠ ['S','F','C','S'], +# ⁠ ['A','D','E','E'] +# ] +# +# Given word = "ABCCED", return true. +# Given word = "SEE", return true. +# Given word = "ABCB", return false. +# +# +# +class Solution(object): + def solver(self, board, word, row, col): + if word == '': + return True + if row < 0 or col < 0 or row >= len(board) or col >= len(board[0]) or word[0] != board[row][col]: + return False + board[row][col] = '#' + res = self.solver(board, word[1:], row+1, col) or\ + self.solver(board,word[1:],row-1, col) or\ + self.solver(board,word[1:],row, col+1) or\ + self.solver(board,word[1:],row, col-1) + + board[row][col] = word[0] + return res + + def exist(self, board, word): + """ + :type board: List[List[str]] + :type word: str + :rtype: bool + """ + row, col = len(board), len(board[0]) + c_nums = row*col + for i in range(c_nums): + if self.solver(board, word, i/col, i%col): + return True + return False + + + diff --git a/8.string-to-integer-atoi.py b/8.string-to-integer-atoi.py new file mode 100644 index 00000000..f1df6f1c --- /dev/null +++ b/8.string-to-integer-atoi.py @@ -0,0 +1,145 @@ +# +# @lc app=leetcode id=8 lang=python +# +# [8] String to Integer (atoi) +# +# https://leetcode.com/problems/string-to-integer-atoi/description/ +# +# algorithms +# Medium (14.48%) +# Total Accepted: 328.2K +# Total Submissions: 2.3M +# Testcase Example: '"42"' +# +# Implement atoi which converts a string to an integer. +# +# The function first discards as many whitespace characters as necessary until +# the first non-whitespace character is found. Then, starting from this +# character, takes an optional initial plus or minus sign followed by as many +# numerical digits as possible, and interprets them as a numerical value. +# +# The string can contain additional characters after those that form the +# integral number, which are ignored and have no effect on the behavior of this +# function. +# +# If the first sequence of non-whitespace characters in str is not a valid +# integral number, or if no such sequence exists because either str is empty or +# it contains only whitespace characters, no conversion is performed. +# +# If no valid conversion could be performed, a zero value is returned. +# +# Note: +# +# +# Only the space character ' ' is considered as whitespace character. +# Assume we are dealing with an environment which could only store integers +# within the 32-bit signed integer range: [−231, 231 − 1]. If the numerical +# value is out of the range of representable values, INT_MAX (231 − 1) or +# INT_MIN (−231) is returned. +# +# +# Example 1: +# +# +# Input: "42" +# Output: 42 +# +# +# Example 2: +# +# +# Input: " -42" +# Output: -42 +# Explanation: The first non-whitespace character is '-', which is the minus +# sign. +# Then take as many numerical digits as possible, which gets 42. +# +# +# Example 3: +# +# +# Input: "4193 with words" +# Output: 4193 +# Explanation: Conversion stops at digit '3' as the next character is not a +# numerical digit. +# +# +# Example 4: +# +# +# Input: "words and 987" +# Output: 0 +# Explanation: The first non-whitespace character is 'w', which is not a +# numerical +# digit or a +/- sign. Therefore no valid conversion could be performed. +# +# Example 5: +# +# +# Input: "-91283472332" +# Output: -2147483648 +# Explanation: The number "-91283472332" is out of the range of a 32-bit signed +# integer. +# Thefore INT_MIN (−231) is returned. +# +# +class Solution(object): + def myAtoi(self, str): + """ + :type str: str + :rtype: int + """ + sign = ['+', '-'] + nums = ['0','1','2','3','4','5','6','7','8','9'] + tmp_str = '' + if str == '': + return 0 + # Remove the whilespace in the front of str. + if len(str) == 1 and str not in nums: + return 0 + str = list(str) + while(str[0] == ' '): + str = list(str) + del str[0] + if len(str) == 0: + return 0 + + str = ''.join(str) + + for s in str: + # Cut the string if not number or sign is met. + if s not in sign+nums: + break + tmp_str = tmp_str + s + # number or sign is not found at first position, return 0. + if tmp_str == '': + return 0 + # check the string when len is 1. + if len(tmp_str) == 1: + if tmp_str in nums: + return int(tmp_str) + return 0 + # check the filtting string is illegal. + if tmp_str[0] == '+' and tmp_str[1] not in nums: + return 0 + if tmp_str[0] == '-' and tmp_str[1] not in nums: + return 0 + + for i in range(len(tmp_str)): + if i == 0 and tmp_str[i] in sign: + continue + if tmp_str[i] in nums: + continue + tmp_str = tmp_str[0:i] + break + + res = int(tmp_str) + bound_num = 2147483648 + if res >= 0: + if res >= bound_num: + res = bound_num-1 + else: + if res < -bound_num: + res = -bound_num + return res + diff --git a/80.remove-duplicates-from-sorted-array-ii.py b/80.remove-duplicates-from-sorted-array-ii.py new file mode 100644 index 00000000..6a99e466 --- /dev/null +++ b/80.remove-duplicates-from-sorted-array-ii.py @@ -0,0 +1,74 @@ +# +# @lc app=leetcode id=80 lang=python +# +# [80] Remove Duplicates from Sorted Array II +# +# https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/description/ +# +# algorithms +# Medium (39.68%) +# Total Accepted: 191.2K +# Total Submissions: 481.7K +# Testcase Example: '[1,1,1,2,2,3]' +# +# Given a sorted array nums, remove the duplicates in-place such that +# duplicates appeared at most twice 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,1,2,2,3], +# +# Your function should return length = 5, with the first five elements of nums +# being 1, 1, 2, 2 and 3 respectively. +# +# It doesn't matter what you leave beyond the returned length. +# +# Example 2: +# +# +# Given nums = [0,0,1,1,1,1,2,3,3], +# +# Your function should return length = 7, with the first seven elements of nums +# being modified to 0, 0, 1, 1, 2, 3 and 3 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]); +# } +# +# +# +class Solution(object): + def removeDuplicates(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + pos = 0 + for n in nums: + if pos < 2 or n > nums[pos-2]: + nums[pos] = n + pos += 1 + return pos diff --git a/81.search-in-rotated-sorted-array-ii.py b/81.search-in-rotated-sorted-array-ii.py new file mode 100644 index 00000000..b8ee35d9 --- /dev/null +++ b/81.search-in-rotated-sorted-array-ii.py @@ -0,0 +1,71 @@ +# +# @lc app=leetcode id=81 lang=python +# +# [81] Search in Rotated Sorted Array II +# +# https://leetcode.com/problems/search-in-rotated-sorted-array-ii/description/ +# +# algorithms +# Medium (32.49%) +# Total Accepted: 160.8K +# Total Submissions: 495K +# Testcase Example: '[2,5,6,0,0,1,2]\n0' +# +# Suppose an array sorted in ascending order is rotated at some pivot unknown +# to you beforehand. +# +# (i.e., [0,0,1,2,2,5,6] might become [2,5,6,0,0,1,2]). +# +# You are given a target value to search. If found in the array return true, +# otherwise return false. +# +# Example 1: +# +# +# Input: nums = [2,5,6,0,0,1,2], target = 0 +# Output: true +# +# +# Example 2: +# +# +# Input: nums = [2,5,6,0,0,1,2], target = 3 +# Output: false +# +# Follow up: +# +# +# This is a follow up problem to Search in Rotated Sorted Array, where nums may +# contain duplicates. +# Would this affect the run-time complexity? How and why? +# +# +# +class Solution(object): + def search(self, nums, target): + """ + :type nums: List[int] + :type target: int + :rtype: bool + """ + left, right = 0, len(nums)-1 + while left<=right: + mid = (left+right)/2 + if nums[mid] == target: + return True + while left=nums[left] and targetnums[mid] and target<=nums[right]: + left = mid + 1 + else: + right = mid - 1 + return False + + + diff --git a/82.remove-duplicates-from-sorted-list-ii.py b/82.remove-duplicates-from-sorted-list-ii.py new file mode 100644 index 00000000..3b3b262e --- /dev/null +++ b/82.remove-duplicates-from-sorted-list-ii.py @@ -0,0 +1,90 @@ +# +# @lc app=leetcode id=82 lang=python +# +# [82] Remove Duplicates from Sorted List II +# +# https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/description/ +# +# algorithms +# Medium (32.36%) +# Total Accepted: 172K +# Total Submissions: 531.2K +# Testcase Example: '[1,2,3,3,4,4,5]' +# +# Given a sorted linked list, delete all nodes that have duplicate numbers, +# leaving only distinct numbers from the original list. +# +# Example 1: +# +# +# Input: 1->2->3->3->4->4->5 +# Output: 1->2->5 +# +# +# Example 2: +# +# +# Input: 1->1->1->2->3 +# Output: 2->3 +# +# +# +# Definition for singly-linked list. +# class ListNode(object): +# def __init__(self, x): +# self.val = x +# self.next = None +''' +class Solution(object): + def deleteDuplicates(self, head): + """ + :type head: ListNode + :rtype: ListNode + """ + if head == None or head.next == None: + return head + head_node = ListNode(None) + head_node.next = head + lst_dict = {} + lst_arr = [] + while head != None: + if head.val not in lst_dict.keys(): + lst_dict[head.val] = 1 + lst_arr.append(head.val) + else: + lst_dict[head.val] = lst_dict[head.val] + 1 + head = head.next + + new_head = ListNode(None) + tr_node = new_head + for k in lst_arr: + if lst_dict[k] > 1: + continue + tmp_node = ListNode(k) + tr_node.next = tmp_node + tr_node = tr_node.next + new_head = new_head.next + return new_head +''' +class Solution(object): + def deleteDuplicates(self, head): + """ + :type head: ListNode + :rtype: ListNode + """ + if head == None or head.next == None: + return head + head_node = ListNode(None) + head_node.next = head + pre = head_node + while head and head.next !=None: + if head.val == head.next.val: + while head and head.next!=None and head.val == head.next.val: + head = head.next + head = head.next + pre.next = head + else: + pre = pre.next + head = head.next + head_node = head_node.next + return head_node diff --git a/86.partition-list.py b/86.partition-list.py new file mode 100644 index 00000000..b26dcc49 --- /dev/null +++ b/86.partition-list.py @@ -0,0 +1,63 @@ +# +# @lc app=leetcode id=86 lang=python +# +# [86] Partition List +# +# https://leetcode.com/problems/partition-list/description/ +# +# algorithms +# Medium (36.74%) +# Total Accepted: 157.9K +# Total Submissions: 429.8K +# Testcase Example: '[1,4,3,2,5,2]\n3' +# +# Given a linked list and a value x, partition it such that all nodes less than +# x come before nodes greater than or equal to x. +# +# You should preserve the original relative order of the nodes in each of the +# two partitions. +# +# Example: +# +# +# Input: head = 1->4->3->2->5->2, x = 3 +# Output: 1->2->2->4->3->5 +# +# +# +# Definition for singly-linked list. +# class ListNode(object): +# def __init__(self, x): +# self.val = x +# self.next = None + +class Solution(object): + def partition(self, head, x): + """ + :type head: ListNode + :type x: int + :rtype: ListNode + """ + head_node = ListNode(None) + head_node_2 = ListNode(None) + pre_low = head_node_2 + pre_high = head_node + while head != None: + tmp = ListNode(head.val) + if head.val < x: + pre_low.next = tmp + pre_low = tmp + else: + pre_high.next = tmp + pre_high = tmp + head = head.next + head_node = head_node.next + pre_low.next = head_node + head_node_2 = head_node_2.next + return head_node_2 + + + + + + diff --git a/89.gray-code.py b/89.gray-code.py new file mode 100644 index 00000000..fdb999ce --- /dev/null +++ b/89.gray-code.py @@ -0,0 +1,64 @@ +# +# @lc app=leetcode id=89 lang=python +# +# [89] Gray Code +# +# https://leetcode.com/problems/gray-code/description/ +# +# algorithms +# Medium (45.30%) +# Total Accepted: 130K +# Total Submissions: 286.9K +# Testcase Example: '2' +# +# The gray code is a binary numeral system where two successive values differ +# in only one bit. +# +# Given a non-negative integer n representing the total number of bits in the +# code, print the sequence of gray code. A gray code sequence must begin with +# 0. +# +# Example 1: +# +# +# Input: 2 +# Output: [0,1,3,2] +# Explanation: +# 00 - 0 +# 01 - 1 +# 11 - 3 +# 10 - 2 +# +# For a given n, a gray code sequence may not be uniquely defined. +# For example, [0,2,3,1] is also a valid gray code sequence. +# +# 00 - 0 +# 10 - 2 +# 11 - 3 +# 01 - 1 +# +# +# Example 2: +# +# +# Input: 0 +# Output: [0] +# Explanation: We define the gray code sequence to begin with 0. +# A gray code sequence of n has size = 2^n, which for n = 0 the size is 2^0 = +# 1. +# Therefore, for n = 0 the gray code sequence is [0]. +# +# +# +class Solution(object): + def grayCode(self, n): + """ + :type n: int + :rtype: List[int] + """ + if n == 0: + return [0] + tmp = self.grayCode(n-1) + res = tmp + [i + 2**(n-1) for i in tmp[::-1]] + return res + diff --git a/90.subsets-ii.py b/90.subsets-ii.py new file mode 100644 index 00000000..2e4332c6 --- /dev/null +++ b/90.subsets-ii.py @@ -0,0 +1,78 @@ +# +# @lc app=leetcode id=90 lang=python +# +# [90] Subsets II +# +# https://leetcode.com/problems/subsets-ii/description/ +# +# algorithms +# Medium (41.88%) +# Total Accepted: 195.2K +# Total Submissions: 466.1K +# Testcase Example: '[1,2,2]' +# +# Given a collection of integers that might contain duplicates, nums, return +# all possible subsets (the power set). +# +# Note: The solution set must not contain duplicate subsets. +# +# Example: +# +# +# Input: [1,2,2] +# Output: +# [ +# ⁠ [2], +# ⁠ [1], +# ⁠ [1,2,2], +# ⁠ [2,2], +# ⁠ [1,2], +# ⁠ [] +# ] +# +# +# +class Solution(object): + ''' + def solver(self, nums, res): + if nums not in res: + res.append(nums) + else: + return + if len(nums)<=1: + return + for i in range(len(nums)): + if i == 0: + tmp_nums = nums[1:] + else: + tmp_nums = nums[0:i]+nums[i+1:] + self.solver(tmp_nums, res) + def subsetsWithDup(self, nums): + """ + :type nums: List[int] + :rtype: List[List[int]] + """ + res = [] + nums.sort() + self.solver(nums, res) + res.append([]) + return res + + def subsetsWithDup(self, nums): + result = [[]] + for num in sorted(nums): + result += [i+[num] for i in result if i+[num] not in result] + return result + ''' + def subsetsWithDup(self, nums): + res = [] + nums.sort() + self.dfs(nums, 0, [], res) + return res + + def dfs(self, nums, index, path, res): + res.append(path) + for i in xrange(index, len(nums)): + if i > index and nums[i] == nums[i-1]: + continue + self.dfs(nums, i+1, path+[nums[i]], res) diff --git a/91.decode-ways.py b/91.decode-ways.py new file mode 100644 index 00000000..d47643c1 --- /dev/null +++ b/91.decode-ways.py @@ -0,0 +1,69 @@ +# +# @lc app=leetcode id=91 lang=python +# +# [91] Decode Ways +# +# https://leetcode.com/problems/decode-ways/description/ +# +# algorithms +# Medium (22.08%) +# Total Accepted: 248.5K +# Total Submissions: 1.1M +# Testcase Example: '"12"' +# +# A message containing letters from A-Z is being encoded to numbers using the +# following mapping: +# +# +# 'A' -> 1 +# 'B' -> 2 +# ... +# 'Z' -> 26 +# +# +# Given a non-empty string containing only digits, determine the total number +# of ways to decode it. +# +# Example 1: +# +# +# Input: "12" +# Output: 2 +# Explanation: It could be decoded as "AB" (1 2) or "L" (12). +# +# +# Example 2: +# +# +# Input: "226" +# Output: 3 +# Explanation: It could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 +# 6). +# [2,6,7,1,2,5] [26, 7, 1, 2, 5] [26, 7, 12, 5] [26, 7, 1, 25] +# [2, 6, 7, 12, 5] [2, 6, 7, 1, 25] +# [26, 71, 25] -> [26, 7, 1, 25] + +# 2 2 6 +# 0 1 1 1 +#2 1 0 1 1 +#2 1 0 +#6 1 0 +class Solution(object): + + def numDecodings(self, s): + """ + :type s: str + :rtype: int + """ + if not s: + return 0 + dp = [0 for i in range(len(s)+1)] + dp[0] = 1 + dp[1] = 1 if 02->3->4->5->NULL, m = 2, n = 4 +# Output: 1->4->3->2->5->NULL +# +# +# +# Definition for singly-linked list. +# class ListNode(object): +# def __init__(self, x): +# self.val = x +# self.next = None + +class Solution(object): + def reverseBetween(self, head, m, n): + """ + :type head: ListNode + :type m: int + :type n: int + :rtype: ListNode + """ + margin = n-m + pre = head_node = ListNode(None) + head_node.next = head + + #pre = head_node + cnt = 0 + while cnt < m-1: + pre = pre.next + head = head.next + cnt += 1 + while margin > 0: + # cut the node + tmp_node = head.next + head.next = tmp_node.next + + # insert + tmp_node.next = pre.next + pre.next = tmp_node + + margin -= 1 + + head_node = head_node.next + #head_node.val = margin + return head_node diff --git a/93.restore-ip-addresses.py b/93.restore-ip-addresses.py new file mode 100644 index 00000000..6efe9c8c --- /dev/null +++ b/93.restore-ip-addresses.py @@ -0,0 +1,49 @@ +# +# @lc app=leetcode id=93 lang=python +# +# [93] Restore IP Addresses +# +# https://leetcode.com/problems/restore-ip-addresses/description/ +# +# algorithms +# Medium (31.05%) +# Total Accepted: 134.4K +# Total Submissions: 432.9K +# Testcase Example: '"25525511135"' +# +# Given a string containing only digits, restore it by returning all possible +# valid IP address combinations. +# +# Example: +# +# +# Input: "25525511135" +# Output: ["255.255.11.135", "255.255.111.35"] +# +# +# +class Solution(object): + def solver(self, s, idx, path, res): + if idx == 4: + if not s: + res.append(path[:-1]) + return + for i in range(1,4): + if i <= len(s): + if i == 1: + self.solver(s[i:], idx+1, path+s[:i]+'.', res) + elif i == 2 and s[0] != '0': + self.solver(s[i:], idx+1, path+s[:i]+'.', res) + elif i == 3 and s[0] != '0' and int(s[:i]) <= 255: + self.solver(s[i:], idx+1, path+s[:i]+'.', res) + + def restoreIpAddresses(self, s): + """ + :type s: str + :rtype: List[str] + """ + res = [] + self.solver(s, 0, '', res) + return res + +