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 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]
'''
class Solution(object):
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
left, right = 0, len(nums)-1
while left <= right:
mid = (left + right) / 2
if target > nums[mid]:
left = mid + 1
else:
right = mid
if left == len(nums) or nums[left] != target:
return [-1, -1]
result = [left]
left, right = 0, len(nums) -1
while left <= right:
mid = (left + right) / 2
if nums[mid] > target:
right = mid
else:
left = mid + 1
result.append(left + 1)
return result
\ No newline at end of file
'''
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
"""
import collections
dict_row, dict_col, dict_cell = collections.defaultdict(set), collections.defaultdict(set), collections.defaultdict(set)
for row_index in range(1, 4):
for col_index in range(1, 4):
for row in range(3*(row_index-1), 3*row_index):
for col in range(3*(col_index-1), 3*col_index):
cell_data = board[row][col]
if cell_data == '.':
continue
if cell_data in dict_row[row] or cell_data in dict_col[col] or cell_data in dict_cell[(row_index, col_index)]:
return False
dict_row[row].add(cell_data)
dict_col[col].add(cell_data)
dict_cell[(row_index, col_index)].add(cell_data)
return True
'''
The count-and-say sequence is the sequence of integers with the first five terms as following:
1. 1
2. 11
3. 21
4. 1211
5. 111221
1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.
Given an integer n, generate the nth term of the count-and-say sequence.
'''
class Solution(object):
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
if n == 1:
return "1"
new_num = ""
count_iter = 1
num = "1"
while count_iter < n:
index_i, index_j = 0, 0
count, new_num = 0, ""
while index_j < len(num):
if num[index_i] != num[index_j]:
new_num += str(count) + str(num[index_i])
count = 0
index_i = index_j
else:
count += 1
index_j += 1
if count > 0:
new_num += str(count) + str(num[index_i])
num = new_num
count_iter += 1
return new_num
# Space: O(1)
# Time: O(N*k) k= length of string
\ No newline at end of file
'''
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.
'''
class Solution(object):
def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
result = []
def recursive(candidates, target, currList, index):
if target < 0:
return
if target == 0:
result.append(currList)
return
for start in range(index, len(candidates)):
recursive(candidates, target - candidates[start], currList + [candidates[start]], start)
recursive(candidates, target, [], 0)
return result
'''
There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
Example 1:
nums1 = [1, 3]
nums2 = [2]
The median is 2.0
Example 2:
nums1 = [1, 2]
nums2 = [3, 4]
The median is (2 + 3)/2 = 2.5
'''
class Solution(object):
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
if len(nums1) > len(nums2):
nums1, nums2 = nums2, nums1
x, y = len(nums1), len(nums2)
low , high = 0, x
while low <= high:
partitionx = (low+high)/2
partitiony = (x+y+1)/2 - partitionx
if partitionx == 0:
maxLeftX = float('-inf')
else:
maxLeftX = nums1[partitionx-1]
if partitionx == x:
minRightX = float('inf')
else:
minRightX = nums1[partitionx]
if partitiony == 0:
maxLeftY = float('-inf')
else:
maxLeftY = nums2[partitiony-1]
if partitiony == y:
minRightY = float('inf')
else:
minRightY = nums2[partitiony]
if maxLeftX <= minRightY and maxLeftY <= minRightX:
if((x+y)%2 == 0):
return (max(maxLeftX, maxLeftY) + min(minRightX, minRightY))/2.0
else:
return max(maxLeftY, maxLeftX)
elif maxLeftX > minRightY:
high = partitionx - 1
else:
low = partitionx + 1
print Solution().findMedianSortedArrays([1,2], [3, 4])
\ No newline at end of file
'''
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]
]
'''
class Solution(object):
def combinationSum2(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
result = []
candidates.sort()
def recursive(candidates, target, currList, index):
if target < 0:
return
if target == 0:
result.append(currList)
return
previous = -1
for start in range(index, len(candidates)):
if previous != candidates[start]:
recursive(candidates, target - candidates[start], currList + [candidates[start]], start+1)
previous = candidates[start]
recursive(candidates, target, [], 0)
return result
\ No newline at end of file
'''
Given an unsorted integer array, find the smallest missing positive integer.
Example 1:
Input: [1,2,0]
Output: 3
Example 2:
Input: [3,4,-1,1]
Output: 2
Example 3:
Input: [7,8,9,11,12]
Output: 1
'''
class Solution(object):
def firstMissingPositive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
index_i = 0
for index_j in range(len(nums)):
if nums[index_j] <= 0:
nums[index_i], nums[index_j] = nums[index_j], nums[index_i]
index_i += 1
for index in range(index_i, len(nums)):
if abs(nums[index]) - 1 < len(nums) and nums[abs(nums[index]) - 1] > 0:
nums[abs(nums[index]) - 1] = -nums[abs(nums[index]) - 1]
for index in range(nums):
if nums[index] > 0:
return index + 1
return len(nums) + 1
\ No newline at end of file
'''
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
'''
class Solution(object):
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
if not height:
return 0
left, right = 0, len(height) - 1
leftMax, rightMax = 0, 0
result = 0
while left < right:
if height[left] < height[right]:
if height[left] > leftMax:
leftMax = height[left]
else:
result += (leftMax - height[left])
left += 1
else:
if height[right] > rightMax:
rightMax = height[right]
else:
result += (rightMax - height[right])
right -= 1
return result
\ No newline at end of file
'''
Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*'.
'?' Matches any single character.
'*' Matches any sequence of characters (including the empty sequence).
The matching should cover the entire input string (not partial).
Note:
s could be empty and contains only lowercase letters a-z.
p could be empty and contains only lowercase letters a-z, and characters like ? or *.
'''
class Solution(object):
def isMatch(self, s, p):
"""
:type s: str
:type p: str
:rtype: bool
"""
if len(p) == 0:
return len(s) == 0
dp = [[False for _ in range(len(p) + 1)] for _ in range(len(s) + 1)]
dp[0][0] = True
for index in range(1,len(dp[0])):
if p[index-1] == '*':
dp[0][index] = dp[0][index-1]
for index_i in range(1, len(dp)):
for index_j in range(1, len(dp[0])):
if s[index_i - 1] == p[index_j - 1] or p[index_j - 1] == '?':
dp[index_i][index_j] = dp[index_i-1][index_j-1]
elif p[index_j-1] == '*':
dp[index_i][index_j] = dp[index_i][index_j-1] or dp[index_i-1][index_j]
else:
dp[index_i][index_j] = False
return dp[len(s)][len(p)]
\ No newline at end of file
'''
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Your goal is to reach the last index in the minimum number of jumps.
Example:
Input: [2,3,1,1,4]
Output: 2
Explanation: The minimum number of jumps to reach the last index is 2.
Jump 1 step from index 0 to 1, then 3 steps to the last index.
'''
class Solution(object):
def jump(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
steps, lastRearch, maxReach = 0, 0 ,0
for index in range(len(nums)):
if index > lastRearch:
lastRearch = maxReach
steps += 1
maxReach = max(maxReach, index + nums[index])
return steps if maxReach == len(nums) - 1 else 0
class Solution(object):
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
if len(nums) == 0:
return []
if len(nums) == 1:
return [nums]
result = []
for index in range(len(nums)):
for p in self.permute(nums[0:index] + nums[index+1:]):
result.append([nums[index]] + p)
return result
\ No newline at end of file
'''
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
'''
class Solution(object):
def rotate(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
n = len(matrix)
if n%2 == 0:
m = n/2
else:
m = n/2 + 1
for i in range(n/2):
for j in range(m):
temp = matrix[i][j]
matrix[i][j] = matrix[n-j-1][i]
matrix[n-j-1][i] = matrix[n-i-1][n-j-1]
matrix[n-i-1][n-j-1] = matrix[j][n-i-1]
matrix[j][n-i-1] = temp
'''
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.
'''
class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
currSum, result = nums[0], nums[0]
for index in range(1, len(nums)):
currSum = max(nums[index], currSum+nums[index])
result = max(result, currSum)
return result
\ No newline at end of file
'''
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]
'''
class Solution(object):
def spiralOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
if not matrix:
return []
R, C = len(matrix), len(matrix[0])
dr = [0, 1, 0, -1]
dc = [1, 0, -1, 0]
result = []
seen = [[False]*C for _ in range(R)]
row = 0
col = 0
di = 0
for _ in range(R*C):
result.append(matrix[row][col])
seen[row][col] = True
rr, cc = row + dr[di], col + dc[di]
if 0 <= rr < R and 0 <= cc < C and not seen[rr][cc]:
row, col = rr, cc
else:
di = (di+1)%4
row, col = row + dr[di], col + dc[di]
return result
\ No newline at end of file
'''
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 considerred overlapping.
'''
# Definition for an interval.
# class Interval(object):
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class compare(object):
def __init__(self, interval):
self.interval = interval
def __lt__(self, other):
if self.interval.start == other.interval.start:
return self.interval.end < other.interval.end
return self.interval.start < other.interval.end
class Solution(object):
def merge(self, intervals):
"""
:type intervals: List[Interval]
:rtype: List[Interval]
"""
intervals = sorted(intervals, key= compare)
# intervals.sort(key=lambda x: x.start)
merged = []
for interval in intervals:
if not merged or merged[-1].end < interval.start:
merged.append(interval)
else:
merged[-1].end = max(merged[-1].end, interval.end)
return merged
# Time: O(N*log(N))
# Space: O(1)
\ No newline at end of file
'''
Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
You may assume that the intervals were initially sorted according to their start times.
Example 1:
Input: intervals = [[1,3],[6,9]], newInterval = [2,5]
Output: [[1,5],[6,9]]
Example 2:
Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
Output: [[1,2],[3,10],[12,16]]
Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10].
'''
# Definition for an interval.
# class Interval(object):
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution(object):
def insert(self, intervals, newInterval):
"""
:type intervals: List[Interval]
:type newInterval: Interval
:rtype: List[Interval]
"""
result = []
for interval in intervals:
if newInterval.start > interval.end:
result.append(interval)
elif newInterval.end < interval.start:
result.append(newInterval)
newInterval = interval
elif newInterval.start <= interval.end or newInterval.end >= interval.start:
newInterval = Interval(min(newInterval.start, interval.start), max(interval.end, newInterval.end))
result.append(newInterval)
return result
\ No newline at end of file
class Solution(object):
def getPermutation(self, n, k):
"""
:type n: int
:type k: int
:rtype: str
"""
nums = []
for index in range(1, n+1):
nums.append(index)
def permute(nums):
if len(nums) == 0:
return []
if len(nums) == 1:
return [nums]
result = []
for index in range(len(nums)):
for p in permute(nums[0:index] + nums[index+1:]):
result.append([nums[index]] + p)
return result
value = permute(nums)[k-1]
result = ""
for val in value:
result += str(val)
return result
\ No newline at end of file
# 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 not head:
return None
tempHead, length = head, 1
while tempHead.next:
length += 1
tempHead = tempHead.next
tempHead.next = head
jump = (length-k)%length
previous = tempHead
while jump > 0:
previous = previous.next
jump -= 1
head = previous.next
previous.next = None
return head
\ No newline at end of file
'''
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?
'''
class Solution(object):
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
dp = [[0 for _ in range(n)] for _ in range(m)]
for index in range(m):
dp[index][0] = 1
for index in range(n):
dp[0][index] = 1
for index_i in range(1, m):
for index_j in range(1, n):
dp[index_i][index_j] = dp[index_i-1][index_j] + dp[index_i][index_j-1]
return dp[m-1][n-1]
\ No newline at end of file
'''
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?
'''
class Solution(object):
def uniquePathsWithObstacles(self, obstacleGrid):
"""
:type obstacleGrid: List[List[int]]
:rtype: int
"""
m, n = len(obstacleGrid), len(obstacleGrid[0])
dp = [[0 for _ in range(n)] for _ in range(m)]
if obstacleGrid[0][0] == 1 or obstacleGrid[m-1][n-1] == 1:
return 0
dp[0][0] = 1
for index in range(1, m):
if obstacleGrid[index][0] == 1:
dp[index][0] = 0
else:
dp[index][0] = dp[index-1][0]
for index in range(1, n):
if obstacleGrid[0][index] == 1:
dp[0][index] = 0
else:
dp[0][index] = dp[0][index-1]
for index_i in range(1, m):
for index_j in range(1, n):
if obstacleGrid[index_i][index_j] == 1:
dp[index_i][index_j] = 0
else:
dp[index_i][index_j] = dp[index_i-1][index_j] + dp[index_i][index_j-1]
return dp[m-1][n-1]
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