leetcode中等.陣列(1-20)python
15. 3Sum(m-1)
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.
class Solution(object): def threeSum(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ result=[] if len(nums)<3: return result nums.sort() for i in range(0, len(nums)): j=i+1 k=len(nums)-1 if i>0 and nums[i]==nums[i-1]: continue while j<k: sum=nums[i]+nums[j]+nums[k] if sum==0: result.append((nums[i], nums[j], nums[k])) k-=1 j+=1 while nums[j]==nums[j-1] and nums[k]==nums[k+1] and j<k: j+=1 elif sum>0: k-=1 while nums[k]==nums[k+1] and j<k: k-=1 else: j+=1 while nums[j]==nums[j-1] and j<k: j+=1 return list(set(result))
16. 3Sum Closest(m-2)
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.
class Solution(object): def threeSumClosest(self, nums, target): length=len(nums) Min=2147483647 nums.sort() for i in range(length-2): if i>0 and nums[i]==nums[i-1]: continue j=i+1 k=length-1 while j<k: sum=nums[i]+nums[j]+nums[k] if abs(sum-target)<abs(Min): Min=sum-target if sum==target: return target elif sum>target: k-=1 else: j+=1 return Min+target
18. 4Sum(m-3)
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
.
class Solution(object):
def fourSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
nums.sort()
res = []
for i in xrange(0, len(nums)):
if i > 0 and nums[i] == nums[i - 1]:
continue
for j in xrange(i + 1, len(nums)):
if j > i + 1 and nums[j] == nums[j - 1]:
continue
start = j + 1
end = len(nums) - 1
while start < end:
sum = nums[i] + nums[j] + nums[start] + nums[end]
if sum < target:
start += 1
elif sum > target:
end -= 1
else:
res.append((nums[i], nums[j], nums[start], nums[end]))
start += 1
end -= 1
while start < end and nums[start] == nums[start - 1]:
start += 1
while start < end and nums[end] == nums[end + 1]:
end -= 1
return res
31. Next Permutation(m-4)
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.
class Solution(object):
def nextPermutation(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
if nums is None or len(nums) <= 1:
return
pos = None
p = len(nums) - 2
# find the first number that is not in correct order
while p >= 0:
if nums[p + 1] > nums[p]:
pos = p
break
p -= 1
if pos is None:
self.reverse(nums, 0, len(nums) - 1)
return
# find the min value in the rest of the array
minPos, minV = pos + 1, nums[pos + 1]
for i in xrange(pos + 1, len(nums)):
if nums[i] <= minV and nums[i] > nums[pos]:
minV = nums[i]
minPos = i
# swap the two above number and reverse the array from `pos`
nums[pos], nums[minPos] = nums[minPos], nums[pos]
self.reverse(nums, pos + 1, len(nums) - 1)
def reverse(self, nums, start, end):
while start < end:
nums[start], nums[end] = nums[end], nums[start]
start += 1
end -= 1
33. Search in Rotated Sorted Array(m-5)
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).
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if not nums:
return -1
left=0
right=len(nums)-1
while left<=right:
mid=(left+right)/2
if nums[mid]==target:
return mid
if nums[mid]>=nums[left]:
if nums[left]<=target<=nums[mid]:
right=mid-1
else:
left=mid+1
else:
if nums[mid]<=target<=nums[right]:
left=mid+1
else:
right=mid-1
return -1
39. Combination Sum(m-6)
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.
class Solution(object):
def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
def DFS(candidates, start, target, path, res):
if target==0:
return res.append(path+[])
for i in range(start, len(candidates)):
if target-candidates[i]>=0:
path.append(candidates[i])
DFS(candidates, i, target-candidates[i], path, res)
path.pop()
res=[]
DFS(candidates, 0, target, [], res)
return res
40. Combination Sum II(m-7)
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.
class Solution(object):
def combinationSum2(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
def dfs(nums, start, visited, target, path, res):
if target==0:
return res.append(path+[])
for i in range(start, len(candidates)):
if i>start and nums[i]==nums[i-1]:
continue
if target - nums[i]<0:
return 0
if i not in visited:
visited.add(i)
path.append(nums[i])
dfs(nums, i+1, visited, target-nums[i], path, res)
path.pop()
visited.discard(i)
candidates.sort()
res=[]
visited=set([])
dfs(candidates, 0, visited, target, [], res)
return res
48. Rotate Image(m-8)
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.
"""
if len(matrix)==0:
return
a=len(matrix)
b=len(matrix[0])
for i in range(a):
for j in range(b/2):
matrix[i][j], matrix[i][b-j-1]=matrix[i][b-j-1], matrix[i][j]
for i in range(0, a):
for j in range(0, b-i-1):
matrix[i][j], matrix[b - 1 - j][a - 1 - i] = matrix[b - 1 - j][a - 1 - i], matrix[i][j]
54. Spiral Matrix(m-9)
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
class Solution(object):
def spiralOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
if len(matrix) == 0 or len(matrix[0]) == 0:
return []
ans = []
left, up, down, right = 0, 0, len(matrix) - 1, len(matrix[0]) - 1
while left <= right and up <= down:
for i in range(left, right + 1):
ans += matrix[up][i],
up += 1
for i in range(up, down + 1):
ans += matrix[i][right],
right -= 1
for i in reversed(range(left, right + 1)):
ans += matrix[down][i],
down -= 1
for i in reversed(range(up, down + 1)):
ans += matrix[i][left],
left += 1
return ans[:(len(matrix) * len(matrix[0]))]
55. Jump Game(m-10)
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.
Determine if you are able to reach the last index.
class Solution(object):
def canJump(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
n=len(nums)
if n==0:
return False
G=nums[0]
for i in range(1, n):
if G<i:
return False
G=max(G, nums[i]+i)
if G>=n-1:
return True
return G>=n-1
56. Merge Intervals(m-11)
Given a collection of intervals, merge all overlapping intervals.
# 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]
"""
ans=[]
for intv in sorted(intervals, key=lambda x:x.start):
if ans and ans[-1].ens>=intv.start:
ans[-1].end=max(ans[-1].end, intv.end)
else:
ans.append(intv)
return ans
59. Spiral Matrix II(m-12)
Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
class Solution(object):
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
ans=[[0]*n for _ in range(n)]
left, right, up, down=0, n-1, 0, n-1
k=1
while left<=right and up<=down:
for i in range(left, right+1):
ans[up][i]=k
k+=1
up+=1
for i in range(up, down+1):
ans[i][right]=k
k+=1
right-=1
for i in reversed(range(left, right+1)):
ans[down][i]=k
k+=1
down-=1
for i in reversed(range(up, down+1)):
ans[i][left]=k
k+=1
left+=1
return ans
62. Unique Paths(m-13)
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
"""
matrix=[[0]*n]*m
for i in range(m):
for j in range(n):
if i==0 or j==0:
matrix[i][j]=1
else:
matrix[i][j]=matrix[i][j-1]+matrix[i-1][j]
return matrix[m-1][n-1]
63. Unique Paths II(m-14)
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])
martix = [[0] * n] * m
for i in range(m):
for j in range(n):
if obstacleGrid[i][j] == 1:
martix[i][j] = 0
else:
if i == 0 and j == 0:
martix[i][j] = 1
elif i == 0:
martix[i][j] = martix[i][j - 1]
elif j == 0:
martix[i][j] = martix[i - 1][j]
else:
martix[i][j] = martix[i - 1][j] + martix[i][j - 1]
return martix[m - 1][n - 1]
64. Minimum Path Sum(m-15)
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.
class Solution(object):
def minPathSum(self, grid):
n = len(grid)
m = len(grid[0])
for i in range(1,n):
grid[i][0] = grid[i-1][0] + grid[i][0] #首先需要尋找左邊界各點的路徑總和
for j in range(1,m):
grid[0][j] = grid[0][j-1] + grid[0][j] #尋找上邊界各點的路徑總和
for i in range(1,n):
for j in range(1,m):
grid[i][j] = min(grid[i-1][j] , grid[i][j-1]) + grid[i][j] #以邊界處為依據一步步推出內部個點的路徑總和
return grid[n-1][m-1]
73. Set Matrix Zeroes(m-16)
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place.
class Solution(object):
def setZeroes(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
m=len(matrix)
n=len(matrix[0])
row=[False for i in range(m)]
col=[False for j in range(n)]
for i in range(m):
for j in range(n):
if matrix[i][j]==0:
row[i]=True
col[j]=True
for i in range(m):
for j in range(n):
if row[i] or col[j]:
matrix[i][j]=0
74. Search a 2D Matrix(m-17)
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.
class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if not matrix:
return False
m=len(matrix)
n=len(matrix[0])
row=m-1
col=0
while row>=0 and col<n:
if target == matrix[row][col]:
return True
elif target > matrix[row][col]:
col+=1
else:
row-=1
return False
75. Sort Colors(m-18)
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.
class Solution(object):
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
if nums==[]:
return
i, l, r=0, 0, len(nums)-1
while i<=r:
if nums[i]==2:
nums[i], nums[r]=nums[r], nums[i]
r-=1
elif nums[i]==0:
nums[i], nums[l]=nums[l], nums[i]
l+=1
i+=1
else:
i+=1
78. Subsets(m-19)
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]]
"""
def dfs(res, tmp, index, nums):
res.append(tmp)
for i in range(index, len(nums)):
dfs(res, tmp+[nums[i]], i+1, nums)
res=[]
dfs(res, [], 0, nums)
return res
79. Word Search(m-20)
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.
class Solution(object):
def exist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
for y in xrange(len(board)):
for x in xrange(len(board[0])):
if self.exit(board, word, x, y, 0):
return True
return False
def exit(self, board, word, x, y, i):
if i == len(word):
return True
if x < 0 or x >= len(board[0]) or y < 0 or y >= len(board):
return False
if board[y][x] != word[i]:
return False
board[y][x] = board[y][x].swapcase()
isexit = self.exit(board, word, x + 1, y, i + 1) or self.exit(board, word, x, y + 1, i + 1) or self.exit(board, word, x - 1, y, i + 1) or self.exit(board, word, x, y - 1, i + 1)
board[y][x] = board[y][x].swapcase()
return isexit