Commit e1017a70 authored by jiang feng's avatar jiang feng
Browse files

Update 22.py, 24.py, 06.py, 23.py, 26.py, 32.py, 25.py, 11.py, 8.py, 19.py,...

Update 22.py, 24.py, 06.py, 23.py, 26.py, 32.py, 25.py, 11.py, 8.py, 19.py, 18.py, 17.py, 16.py, 15.py, 14.py, 4.py, 46.py, 48.py, 53.py, 45.py, 44.py, 42.py, 60.py, 05.py, 03.py, 41.py, 36.py, 65.py, 34.py, 33.py, 31.py, 70.py, 56.py, 54.py, 73.py, 40.py, 78.py, 30.py, 72.py, 66.py, 64.py, 63.py, 74.py, 81.py, 86.py, 85.py, 83.py, 87.py, 79.py, 93.py, 92.py, 82.py, 94.py, 62.py, TwoSum.py, 90.py, 80.py, 91.py, 67.py, 39.py, 38.py, 71.py, 95.py, 10.py, 75.py, 61.py, 57.py, 97.py, 99.py, 98.py files
parents
'''
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.
'''
class Solution(object):
def minPathSum(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
if not grid:
return 0
row, col = len(grid), len(grid[0])
dp = [[0 for _ in range(col)] for _ in range(row)]
dp[0][0] = grid[0][0]
for index in range(1, row):
dp[index][0] = dp[index-1][0] + grid[index][0]
for index in range(1, col):
dp[0][index] = dp[0][index-1] + grid[0][index]
print dp
for index_i in range(1, row):
for index_j in range(1, col):
dp[index_i][index_j] = min(dp[index_i-1][index_j], dp[index_i][index_j-1]) + grid[index_i][index_j]
return dp[row-1][col-1]
\ No newline at end of file
'''
Validate if a given string is numeric.
Some examples:
"0" => true
" 0.1 " => true
"abc" => false
"1 a" => false
"2e10" => true
Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one.
'''
class Solution(object):
def isNumber(self, s):
"""
:type s: str
:rtype: bool
"""
s = s.strip()
try:
if isinstance(float(s),float) or isinstance(int(s),int):
return True
except Exception as e:
return False
# Time: O(1)
# Space: O(1)
\ No newline at end of file
'''
Given a non-empty array of digits representing a non-negative integer, plus one to the integer.
The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.
You may assume the integer does not contain any leading zero, except the number 0 itself.
Example 1:
Input: [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123
'''
class Solution(object):
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
result = []
if not digits:
return []
carry = 1
new_digits = digits[::-1]
for index in range(len(new_digits)):
new_digits[index], carry = (new_digits[index] + carry)%10, (new_digits[index] + carry)/10
if carry > 0:
new_digits.append(carry)
return new_digits[::-1]
Time: O(N)
Space: O(1)
\ No newline at end of file
'''
Given two binary strings, return their sum (also a binary string).
The input strings are both non-empty and contains only characters 1 or 0.
Example 1:
Input: a = "11", b = "1"
Output: "100"
Example 2:
Input: a = "1010", b = "1011"
Output: "10101"
'''
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
result = ""
carry = 0
index_a, index_b = len(a)-1, len(b)-1
while index_a >= 0 and index_b >= 0:
result = (int(a[index_a]) + int(b[index_b]) + carry)%2 + result
carry = (int(a[index_a]) + int(b[index_b]) + carry)%2
index_a -= 1
index_b -= 1
if index_a >= 0:
while index_a >= 0:
result = (int(a[index_a]) + carry)%2 + result
carry = (int(a[index_a]) + carry)%2
index_a -= 1
elif index_b >= 0:
while index_b >= 0:
result = (int(b[index_b]) + carry)%2 + result
carry = (int(b[index_b]) + carry)%2
index_b -= 1
else:
if carry == 1:
result = str(carry) + result
return result
\ No newline at end of file
'''
You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Note: Given n will be a positive integer.
Example 1:
Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
'''
class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
if n == 0:
return 0
dp = [0]*n
dp[0], dp[1] = 1, 2
for index in range(2, n):
dp[index] = dp[index-1] + dp[index-2]
return dp[n-1]
# Time: O(N)
# Space: O(N)
'''
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
'''
class Solution(object):
def simplifyPath(self, path):
"""
:type path: str
:rtype: str
"""
result = "/"
stack = []
index = 0
while index < len(path):
if path[index] == '/':
index += 1
continue
curr_str = ""
while index < len(path) and path[index] != '/':
curr_str += path[index]
index += 1
if curr_str == '.' or curr_str == "":
index += 1
continue
elif curr_str == "..":
if stack:
stack.pop()
index += 1
else:
stack.append(curr_str)
index += 1
for index in range(len(stack)):
if index != len(stack) -1:
result += stack[index] + '/'
else:
result += stack[index]
return result
# Time: O(N)
# Space: O(N)
\ No newline at end of file
'''
Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2.
You have the following 3 operations permitted on a word:
Insert a character
Delete a character
Replace a character
Example 1:
Input: word1 = "horse", word2 = "ros"
Output: 3
Explanation:
horse -> rorse (replace 'h' with 'r')
rorse -> rose (remove 'r')
rose -> ros (remove 'e')
Example 2:
Input: word1 = "intention", word2 = "execution"
Output: 5
Explanation:
intention -> inention (remove 't')
inention -> enention (replace 'i' with 'e')
enention -> exention (replace 'n' with 'x')
exention -> exection (replace 'n' with 'c')
exection -> execution (insert 'u')
'''
class Solution(object):
def minDistance(self, word1, word2):
"""
:type word1: str
:type word2: str
:rtype: int
"""
m , n = len(word1), len(word2)
dp = [[0 for _ in range(n+1)] for _ in range(m+1)]
for index_i in range(m+1):
for index_j in range(n+1):
if index_i == 0:
dp[index_i][index_j] = index_j
elif index_j == 0:
dp[index_i][index_j] = index_i
elif word1[index_i-1] == word2[index_j-1]:
dp[index_i][index_j] = dp[index_i-1][index_j-1]
else:
dp[index_i][index_j] = 1 + min(dp[index_i-1][index_j], dp[index_i-1][index_j-1], dp[index_i][index_j-1])
return dp[m][n]
\ No newline at end of file
class Solution(object):
def setZeroes(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
col0 = 1
for row in range(len(matrix)):
if matrix[row][0] == 0:
col0 = 0
for col in range(1, len(matrix[0])):
if matrix[row][col] == 0:
matrix[row][0] = 0
matrix[0][col] = 0
for row in range(len(matrix)-1, -1, -1):
for col in range(len(matrix[0])-1, 0, -1):
if matrix[row][0] == 0 or matrix[0][col] == 0:
matrix[row][col] = 0
if col0 == 0:
matrix[row][0] = 0
'''
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
'''
class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if not matrix:
return 0
left, right = 0, len(matrix[0])-1
while left < len(matrix) and right >= 0:
if matrix[left][right] == target:
return True
elif matrix[left][right] < target:
left += 1
else:
right -= 1
return False
\ No newline at end of file
'''
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]
'''
class Solution(object):
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
zero, last = 0, len(nums)-1
index = 0
while index <= last:
if nums[index] == 1:
index += 1
elif nums[index] == 0:
nums[index], nums[zero] = nums[zero], nums[index]
index += 1
zero += 1
elif nums[index] == 2:
nums[last], nums[index] = nums[index], nums[last]
last -= 1
\ No newline at end of file
'''
Given a set of distinct integers, nums, return all possible subsets (the power set).
'''
class Solution(object):
def subsets(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
result = [[]]
for num in nums:
for j in range(len(result)):
result.append(result[j] + [num])
return result
\ No newline at end of file
'''
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 exist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
result = False
for row in range(len(board)):
for col in range(len(board[0])):
if self.dfs(board, word, row, col, 0):
return True
return False
def dfs(self, board, word, row, col, curr_len):
if row < 0 or col < 0 or row >= len(board) or col >= len(board[0]):
return False
if board[row][col] == word[curr_len]:
c = board[row][col]
board[row][col] = '#'
if curr_len == len(word) - 1:
return True
elif (self.dfs(board, word, row-1, col, curr_len+1) or self.dfs(board, word, row+1, col, curr_len+1) or self.dfs(board, word, row, col-1, curr_len+1) or self.dfs(board, word, row, col+1, curr_len+1)):
return True
board[row][col] = c
return False
\ No newline at end of file
class Solution:
def myAtoi(self, str):
"""
:type str: str
:rtype: int
"""
str = str.strip()
number = ""
for x in str:
if x.isalpha() and number == "":
return 0
elif x.isalpha():
break
elif x == ".":
break
elif x == " ":
break
elif (x == "+" or x == "-") and number == "":
number = number + x
elif (x == "+" or x == "-") and number != "":
break
elif (x == "+" or x == "-") and (number[-1] == "+" or number[-1] == "-"):
return 0
elif (x == "+" or x == "-") and ("+" in number or "-" in number):
break
elif x.isdigit():
number = number + x
if number == "" or number == "+" or number == "-":
return 0
else:
if int(number) > ((2**31)-1):
return (2**31)-1
elif int(number) < -(2**31):
return -(2**31)
else:
return int(number)
\ No newline at end of file
'''
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.
'''
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) <= 2:
return len(nums)
prev, curr = 1, 2
while curr < len(nums):
if nums[prev] == nums[curr] and nums[curr] == nums[prev-1]:
curr += 1
else:
prev += 1
nums[prev] = nums[curr]
curr += 1
return prev+1
'''
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
'''
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
if nums[left] < nums[mid]:
if nums[left] <= target < nums[mid]:
right = mid - 1
else:
left = mid + 1
elif nums[mid] < nums[left]:
if nums[mid] < target <= nums[right]:
left = mid + 1
else:
right = mid -1
else:
left += 1
return False
\ No newline at end of file
'''
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 not head:
return None
result = ListNode(0)
ans = result
curr = head
while curr:
value = curr.val
count = 0
while curr and curr.val == value:
curr = curr.next
count += 1
if count == 1:
result.next = ListNode(value)
result = result.next
return ans.next
\ No newline at end of file
'''
Given a sorted linked list, delete all duplicates such that each element appear only once.
Example 1:
Input: 1->1->2
Output: 1->2
Example 2:
Input: 1->1->2->3->3
Output: 1->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 not head:
return None
curr = head
while curr and curr.next:
if curr.val == curr.next.val:
curr.next = curr.next.next
else:
curr = curr.next
return head
\ No newline at end of file
'''
Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.
Example:
Input:
[
["1","0","1","0","0"],
["1","0","1","1","1"],
["1","1","1","1","1"],
["1","0","0","1","0"]
]
Output: 6
'''
class Solution(object):
def largestRectangleArea(self, heights):
"""
:type heights: List[int]
:rtype: int
"""
if not heights:
return 0
stack = []
result, index = 0, 0
while index < len(heights):
if not stack or heights[index] >= heights[stack[-1]]:
stack.append(index)
index += 1
else:
curr = stack.pop()
if not stack:
area = heights[curr]*index
else:
area = heights[curr] * (index-stack[-1]-1)
result = max(result, area)
while stack:
curr = stack.pop()
if not stack:
area = heights[curr]*index
else:
area = heights[curr] * (index-stack[-1]-1)
result = max(result, area)
return result
def maximalRectangle(self, matrix):
"""
:type matrix: List[List[str]]
:rtype: int
"""
if not matrix:
return 0
m, n = len(matrix), len(matrix[0])
heights = [0 for index in range(n)]
result = 0
for index_i in range(m):
for index_j in range(n):
if matrix[index_i][index_j] != '0':
heights[index_j] = heights[index_j] + 1
else:
heights[index_j] = 0
result = max(result, self.largestRectangleArea(heights))
return result
\ No newline at end of file
'''
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
"""
if not head or not head.next:
return head
left, right = ListNode(0), ListNode(0)
leftPtr, rightPtr = left, right
while head:
if head.val < x:
leftPtr.next = ListNode(head.val)
leftPtr = leftPtr.next
else:
rightPtr.next = ListNode(head.val)
rightPtr = rightPtr.next
head = head.next
if not left.next:
return right.next
elif not right.next:
return left.next
else:
leftPtr.next = right.next
return left.next
# Time: O(N)
# Space: O(N)
\ No newline at end of file
'''
Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrings recursively.
Below is one possible representation of s1 = "great":
great
/ \
gr eat
/ \ / \
g r e at
/ \
a t
To scramble the string, we may choose any non-leaf node and swap its two children.
For example, if we choose the node "gr" and swap its two children, it produces a scrambled string "rgeat".
rgeat
/ \
rg eat
/ \ / \
r g e at
/ \
a t
We say that "rgeat" is a scrambled string of "great".
'''
class Solution(object):
def __init__(self):
self.cache = {}
def isScramble(self, s1, s2):
if s1 == s2:
return True
if s1+s2 in self.cache:
return self.cache[s1+s2]
if len(s1) != len(s2) or sorted(s1) != sorted(s2):
self.cache[s1+s2] = False
return False
for index in range(1, len(s1)):
if self.isScramble(s1[:index], s2[:index]) and self.isScramble(s1[index:], s2[index:]):
self.cache[s1+s2] =True
return True
if self.isScramble(s1[:index], s2[-index:]) and self.isScramble(s1[index:], s2[0:-index]):
self.cache[s1+s2] = True
return True
self.cache[s1+s2] =False
return False
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment