leetcode 部分題解(python)
215. Kth Largest Element in an Array
題目鏈接:https://leetcode.com/problems/kth-largest-element-in-an-array/#/description
思路_第k大的數
利用快速排序的思想;從數組S中隨機找出一個元素X,把數組分爲兩部分Sa和Sb。Sa中的元素大於等於X,Sb中元素小於X。這時有兩種情況:
1. Sa中元素的個數小於k,則Sb中的第k-|Sa|個元素即爲第k大數;
2. Sa中元素的個數大於等於k,則返回Sa中的第k大數。時間複雜度近似爲O(n)
class Solution(object):
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
if len(nums)==1:
return nums[0]
target = nums[0]
i,j = 0,len(nums)-1
while i<j:
while i<j and nums[j]>=target:
j -= 1
nums[i] = nums[j]
while i<j and nums[i]<=target:
i += 1
nums[j] = nums[i]
nums[i] = target
right = len(nums)-j
# print(right)
if right==k:
return nums[j]
elif right>k:
return self.findKthLargest(nums[j+1:],k)
else:
print(j)
return self.findKthLargest(nums[:j],k-right)
57. Insert Interval
題目鏈接:https://leetcode.com/problems/insert-interval/?tab=Description
思路_鏈表insert
代碼:
def insert(self, intervals, newInterval):
"""
:type intervals: List[Interval]
:type newInterval: Interval
:rtype: List[Interval]
"""
ans =[]
if len(intervals)==0:
ans.append(newInterval)
return ans
pos = 0
for inte in intervals:
if inte.start>newInterval.end:
ans.append(inte)
elif inte.end<newInterval.start:
ans.append(inte)
pos+=1
else:
newInterval.start = min(newInterval.start,inte.start)
newInterval.end = max(newInterval.end,inte.end)
ans.insert(pos,newInterval)
return ans
56. Merge Intervals
題目鏈接:http://write.blog.csdn.net/mdeditor#!postId=53885139
lambda排序
參考網址:http://www.cnblogs.com/zuoyuan/p/3782028.html
通過 operator 模塊提供的函數還可以實現多重排序的功能。比如,先按 grade 排序再按 age 排序:
sorted(student_tuples, key=itemgetter(1,2))
[(‘john’, ‘A’, 15), (‘dave’, ‘B’, 10), (‘jane’, ‘B’, 12)]sorted(student_objects, key=attrgetter(‘grade’, ‘age’))
[(‘john’, ‘A’, 15), (‘dave’, ‘B’, 10), (‘jane’, ‘B’, 12)]
28. Implement strStr()
題目鏈接:https://leetcode.com/problems/implement-strstr/?tab=Description
思路:查找子串
在一個序列中找到子串並且返回下標索引位置
代碼:
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
if haystack==None or needle==None:
return -1
hlen = len(haystack)
nlen = len(needle)
for i in range(0,hlen-nlen+1):
j = 0
while j<nlen:
if needle[j]==haystack[j+i]:
j+=1
else:
break
if j==nlen:
return i
return -1
1. Two Sum
題目鏈接:https://leetcode.com/problems/two-sum/?tab=Description
思路:哈希
在一個序列裏面找到兩個數使得和爲目標值,並且返回兩個數的下標
代碼:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
def twoSum(self, num, target):
dict = {}
for i in range(len(num)):
x = num[i]
if target-x in dict:
return (dict[target-x]+1, i+1)
dict[x] = i
92. Reverse Linked List II
題目鏈接:https://leetcode.com/problems/reverse-linked-list-ii/?tab=Description
思路_子鏈表翻轉燒腦
代碼:
def reverseBetween(self, head, m, n):
"""
:type head: ListNode
:type m: int
:type n: int
:rtype: ListNode
"""
if head==None or head.next==None or m==n:
return head
L = ListNode(0)
L.next = head
cur = L
for i in range(m-1):
cur = cur.next
p = cur.next
for i in range(n-m):
tem = cur.next
cur.next = p.next
p.next = p.next.next
cur.next.next = tem
return L.next
279. Perfect Squares
題目鏈接:https://leetcode.com/problems/perfect-squares/?tab=Description
題意:計算當前數字最少可以由多少個平方數相加得到
思路_動態規劃
維護一個數組d[n],d[i]表示數字i最少可以由多少個平方數相加得到,初始化d[0]=0,其餘爲max,動態更新方程可表示爲:d[i+j*j] = max(d[i+j*j],d[i]+1)
代碼:
def numSquares(self, n):
"""
:type n: int
:rtype: int
"""
d = [100]*(n+1)
d[0] = 0
d[1] = 1
for i in range(0,n+1):
for j in range(0,n):
if i+j*j<=n:
d[i+j*j] = min(d[i+j*j],d[i]+1)
else:
break
return d[n]
————
129. Sum Root to Leaf Numbers
題目鏈接:https://leetcode.com/problems/sum-root-to-leaf-numbers/?tab=Description
題意:找到根節點到葉節點的所有路徑組成的數字,求和之
思路_二叉樹-DFS
代碼同:https://leetcode.com/problems/binary-tree-paths/?tab=Description
257. Binary Tree Paths
題目鏈接:https://leetcode.com/problems/binary-tree-paths/?tab=Description
題意:輸出根節點到葉節點的所有路徑
思路_二叉樹-DFS
代碼:
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
self.ans = []
if root==None:
return self.ans
def dfs(root,path):
if root.left==None and root.right==None:
self.ans.append(path)
if root.left:
dfs(root.left,path+"->"+str(root.left.val))
if root.right:
dfs(root.right,path+"->"+str(root.right.val))
dfs(root,str(root.val))
return self.ans
110. Balanced Binary Tree
題目鏈接:https://leetcode.com/problems/balanced-binary-tree/?tab=Description
題意:驗證是否是二叉平衡樹(任意節點的兩個子樹高度差最多爲1)
思路_二叉樹深度
代碼:
class Solution(object):
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if root == None:
return True
if abs((self.depth(root.left)-self.depth(root.right)))>1:
return False
else:
return self.isBalanced(root.left) and self.isBalanced(root.right)
def depth(self, r):
if r==None:
return 0
else:
return max(self.depth(r.left), self.depth(r.right))+1
24. Swap Nodes in Pairs
題目鏈接:https://leetcode.com/problems/swap-nodes-in-pairs/?tab=Description
題意:交換鏈表裏面相鄰的兩個節點,空間恆定
思路鏈表遞歸
代碼:
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head==None or head.next==None:
return head
nex = head.next
tem = nex.next
nex.next = head
head.next = self.swapPairs(tem)
return nex
342. Power of Four
題目鏈接:https://leetcode.com/problems/power-of-four/?tab=Solutions
題意:判斷一個數是否是4的冪
思路_二進制
The basic idea is from power of 2, We can use “n&(n-1) == 0” to determine if n is power of 2. For power of 4, the additional restriction is that in binary form, the only “1” should always located at the odd position. For example, 4^0 = 1, 4^1 = 100, 4^2 = 10000. So we can use “num & 0x55555555==num” to check if “1” is located at the odd position.
代碼:
return (num > 0) && ((num & (num - 1)) == 0) && ((num & 0x55555555) == num)
416. Partition Equal Subset Sum
題目鏈接:https://leetcode.com/problems/partition-equal-subset-sum/
題意:驗證一個數組是否存在兩個子集,使得兩個子集的和相等。
思路:_01揹包問題
參照揹包的博文
代碼:
class Solution(object):
def canPartition(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
n = len(nums)
sum_num = sum(nums)
if sum_num%2!=0:
return False
# print(sum_num)
result = [[0]*sum_num for i in range(n+1)]
for i in range(1,n+1):
for j in range(nums[i-1],int(sum_num/2)+1):
result[i][j] = max([result[i-1][j],result[i-1][j-nums[i-1]]+nums[i-1]])
if result[n][int(sum_num/2)]==sum_num/2:
return True
else:
return False
334. Increasing Triplet Subsequence
題目鏈接:https://leetcode.com/problems/increasing-triplet-subsequence/
題意:在一個無序的序列中找到一個長度爲3的遞增子序列。
思路: if_elif_else
我特麼已經蠢到這種題都不會了,維護一個最小數a和次小數b,遍歷到第三個數c滿足c>b 返回Ture
代碼:
class Solution(object):
def increasingTriplet(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
if len(nums)<3:
return False
max_num = max(nums)
c1 = max_num
c2 = max_num
for i in nums:
if i <= c1:
c1 = i
elif i<=c2:
c2 = i
else:
return True
return False
Binary Tree Level Order Traversal II
題目鏈接:https://leetcode.com/problems/binary-tree-level-order-traversal-ii/
思路queue層次遍歷
題意,就是層次遍歷,不過是從bottom to up
代碼:
class Solution(object):
def levelOrderBottom(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if root==None:
return []
results = []
queue = [root]
while queue:
cur_li = []
for i in range(0,len(queue)):
cur = queue.pop(0)
cur_li.append(cur.val)
if cur.left!=None:
queue.append(cur.left)
if cur.right!=None:
queue.append(cur.right)
results.append(cur_li)
return [results[i] for i in range(len(results)-1,-1,-1)]
Search a 2D Matrix II
題目鏈接:https://leetcode.com/problems/search-a-2d-matrix-ii/
思路_面試題
題意:給一個n*m的矩陣,每一行,每一列都從小到大的排列,然後查找target這個數是否存在矩陣中。
腦子不靈活,對每一行二分查找,時間複雜度也要nlogn,,,面試題怎麼會這麼做呢?(我簡直蠢到家)
從右上角開始, 比較target 和 matrix[i][j]的值. 如果小於target, 則該行不可能有此數, 所以i++; 如果大於target, 則該列不可能有此數, 所以j–. 遇到邊界則表明該矩陣不含target.
代碼:
class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
n = len(matrix)
if n==0:
return False
m = len(matrix[0])-1
if m==-1:
return False
i = 0
while m>=0 and i<n:
if matrix[i][m]>target:
m -= 1
elif matrix[i][m]<target:
i +=1
else:
return True
return False
53. Maximum Subarray
題目鏈接:https://leetcode.com/problems/maximum-subarray/
思路_經典的DP問題:
題意:給定一個序列,要找到和最大的那個子序列,並且返回該子序列之和。
維護兩個列表,local[i]即包含當前元素的局部最大和值,DP求local[i]時,local[i] = max(local[i-1]+nums[i],nums[i]) ;
全局最優值globa[i] = max(globa[i-1],local[i]),即先找到包含當前值的局部最優值local[i],當前的全局最優值globa[i]即爲不包含當前值的全局最優與當前局部最優的最大值。
代碼:
class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
local = [0]*len(nums)
globa = [0]*len(nums)
local[0] = nums[0]
globa[0] = nums[0]
for i in range(1,len(nums)):
local[i] = max(local[i-1]+nums[i],nums[i])
globa[i] = max(globa[i-1],local[i])
return max(local[-1],globa[-1])
235. Lowest Common Ancestor of a Binary Search Tree
題目鏈接:https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/
思路二叉搜索樹遞歸:
題意:求二叉搜索樹(!)任意兩個節點的最低共有祖先。
對於二叉搜索樹,公共祖先的值一定大於等於較小的節點,小於等於較大的節點。換言之,在遍歷樹的時候,如果當前結點大於兩個節點,則結果在當前結點的左子樹裏,如果當前結點小於兩個節點,則結果在當前節點的右子樹裏。
代碼:
class Solution(object):
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
if root==None:
return None
if root.val>p.val and root.val>q.val:
return self.lowestCommonAncestor(root.left, p, q)
if root.val<p.val and root.val<q.val:
return self.lowestCommonAncestor(root.right, p, q)
return root
202. Happy Number
題目鏈接:https://leetcode.com/problems/happy-number/
思路_智力題:
給定一個數,判斷這個數是不是happy number;即循環的做每一位的平方和,直到最後得到1這個數。
基本方法就是維護一個列表,每次出現一個新的數,則加到列表裏面,如果當前這個已經存在列表中了則返回false; 如果不存在列表中則添加,若得到1則返回true。
代碼:
class Solution(object):
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
resulst = [n]
while 1:
s = 0
n = resulst[-1]
while n:
cur = n%10
n /=10
s += cur**2
if s in resulst and s!=1:
return False
elif s not in resulst and s!=1:
resulst.append(s)
else:
return True
Sum of Two Integers
題目鏈接:https://leetcode.com/problems/sum-of-two-integers/
題目翻譯:
計算兩個整數a和b的和,但是不能使用運算符加號和減號。
比如:給定a=1,b=2,返回3。
思路_(位操作):
既然不能使用加法和減法,那麼就用位操作。下面以計算5+4的例子說明如何用位操作實現加法:
1. 用二進制表示兩個加數,a=5=0101,b=4=0100;
2. 用and(&)操作得到所有位上的進位carry=0100;
3. 用xor(^)操作找到a和b不同的位,賦值給a,a=0001;
4. 將進位carry左移一位,賦值給b,b=1000;
5. 循環直到進位carry爲0,此時得到a=1001,即最後的sum。
上面思路還算正常,然而對於Python就有點麻煩了。因爲Python的整數不是固定的32位,所以需要做一些特殊的處理,具體見代碼吧。
代碼裏的將一個數對0x100000000取模(注意:Python的取模運算結果恆爲非負數),是希望該數的二進制表示從第32位開始到更高的位都同是0(最低位是第0位),以在0-31位上模擬一個32位的int。
class Solution(object):
def getSum(self, a, b):
"""
:type a: int
:type b: int
:rtype: int
"""
while b != 0:
carry = a & b
a = (a ^ b) % 0x100000000
b = (carry << 1) % 0x100000000
return a if a <= 0x7FFFFFFF else a | (~0x100000000+1)
Roman to Integer
題目鏈接:https://oj.leetcode.com/problems/roman-to-integer/
思路:
羅馬數字是最古老的數字表示方式,比阿拉伯數組早2000多年,起源於羅馬
羅馬數字有如下符號:
基本字符IVXLCDM對應阿拉伯數字1510501005001000
計數規則:
1. 相同的數字連寫,所表示的數等於這些數字相加得到的數,例如:III = 3
2. 小的數字在大的數字右邊,所表示的數等於這些數字相加得到的數,例如:VIII = 8
3. 小的數字,限於(I、X和C)在大的數字左邊,所表示的數等於大數減去小數所得的數,例如:IV = 4
4. 正常使用時,連續的數字重複不得超過三次
5. 在一個數的上面畫橫線,表示這個數擴大1000倍(本題只考慮3999以內的數,所以用不到這條規則)
其次,羅馬數字轉阿拉伯數字規則(僅限於3999以內):
從前向後遍歷羅馬數字,如果某個數比前一個數小,則加上該數。反之,減去前一個數的兩倍然後加上該數
House Robber III
題目連接:https://leetcode.com/problems/house-robber-iii/
思路_(DP):
動態規劃,因爲當前的計算需要依賴之前的結果,那麼我們對於某一個節點a,如果其左子節點b存在,我們通過遞歸調用函數,算出不包含左子節點b返回的值,同理,如果右子節點c存在,算出不包含右子節點c返回的值,那麼此節點的最大值可能有兩種情況,一種是該節點a值加上不包含左子節點b和右子節點c的返回值之和,另一種是左右子節點返回值之和而不包含當期節點值,
class Solution(object):
def rob(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def dsf(root):
if not root:
return [0,0]
leftr = dsf(root.left)
rightr = dsf(root.right)
nocurr = leftr[1]+rightr[1]
cur = leftr[0]+rightr[0] + root.val
maxval = max(cur,nocurr)
return [nocurr,maxval]
return dsf(root)[1]
Serialize and Deserialize BST
題目鏈接:https://leetcode.com/problems/serialize-and-deserialize-bst/#
思路_(序列化、queue_BFS):
序列化就是將一個數據結構或物體轉化爲一個位序列,可以存進一個文件或者內存緩衝器中,然後通過網絡連接在相同的或者另一個電腦環境中被還原,還原的過程叫做去序列化。
層序遍歷的非遞歸解法:藉助queue來做,本質是BFS算法
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"""
if not root:
return '{}'
val = root.val
index = 0
queue = [root]
while index <len(queue):
if queue[index] is not None:
queue.append(queue[index].left)
queue.append(queue[index].right)
index +=1
while queue[-1] is None:
queue.pop()
re = ''
for i in range(0,len(queue)-1):
if queue[i] is not None:
re += str(queue[i].val) + ','
else:
re +='#,'
re='{'+re+str(queue[-1].val)+'}'
return re
def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode
"""
data = data.strip('\n')
if data == '{}':
return None
vals = data[1:-1].split(',')
root = TreeNode(int(vals[0]))
queue = [root]
isLeftChild = True
index = 0
for val in vals[1:]:
if val is not '#':
node = TreeNode(int(val))
if isLeftChild:
queue[index].left = node
else:
queue[index].right = node
queue.append(node)
if not isLeftChild:
index += 1
isLeftChild = not isLeftChild
return root
459. Repeated Substring Pattern
題目鏈接:https://leetcode.com/problems/repeated-substring-pattern/
思路_(KMP_next數組):
題意:給定一個非空字符串,判斷它是否可以通過自身的子串重複若干次構成。你可以假設字符串只包含小寫英文字母,並且長度不會超過10000
記字符串長度爲size,利用KMP算法求next數組,記next數組的最後一個元素爲p
若p > 0 並且 size % (size - p) == 0,返回True
code:
class Solution(object):
def repeatedSubstringPattern(self, str):
"""
:type str: str
:rtype: bool
"""
k=-1
j=0
next = [0]*(len(str)+1)
next[0]=-1
while (j<len(str)):
if k==-1 or str[j]==str[k]:
j+=1
k+=1
next[j]=k
else:
k = next[k]
l = next[-1]
return len(str)%(len(str)-l)==0 and l>0
關於next數組很多代碼裏面求解的是當前字符的前面所有字符的最長前後匹配子串;該解題部分求取了當前位字符的最長匹配子串,只需要將next數組右移一位即可。關於next數組的具體求法參考:http://blog.csdn.net/v_july_v/article/details/7041827
46. Permutations
題目鏈接:https://leetcode.com/problems/permutations/
思路_(遞歸全排列):
可以將這個排列問題畫成圖形表示,即排列枚舉樹,比如下圖爲{1,2,3}的排列枚舉樹,此樹和我們這裏介紹的算法完全一致;
不斷將每個元素放作第一個元素,然後將這個元素作爲前綴,並將其餘元素繼續全排列(遞歸調用即可)
代碼:
class Solution(object):
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
re = []
def perm(num,k,l):
if k==l:
re.append(list(num))
else:
for i in range(k,l):
num[i],num[k]=num[k],num[i]
perm(num,k+1,l)
num[i],num[k]=num[k],num[i]
perm(nums,0,len(nums))
return re
405. Convert a Number to Hexadecimal
題目鏈接:https://leetcode.com/problems/convert-a-number-to-hexadecimal/
思路_(進制數轉化):
將數字轉化爲16進制字符串,負數採用補碼錶示。
只需要將負數轉換爲無符號短整型即可,即負數本身+100000000000000000000000000000000(0x100000000
)
代碼:
class Solution(object):
def toHex(self, num):
"""
:type num: int
:rtype: str
"""
ans = []
hexs = '0123456789abcdef'
if num < 0: num += 0x100000000
while num:
ans.append(hexs[num % 16])
num /= 16
t=''
for i in range(len(ans)-1,-1,-1):
t+=str(ans[i])
return t if ans else '0'
96. Unique Binary Search Trees
題目鏈接:https://leetcode.com/problems/unique-binary-search-trees/
思路_(DP):
n個點中每個點都可以作爲root,當 i 作爲root時,小於 i 的點都只能放在其左子樹中,大於 i 的點只能放在右子樹中,此時只需求出左、右子樹各有多少種,二者相乘即爲以 i 作爲root時BST的總數。
利用動態規劃的思想,維護數組results, results[i]表示含有i個數的BST總數
代碼:
class Solution(object):
def numTrees(self, n):
"""
:type n: int
:rtype: int
"""
results = [0]*(n+1)
results[0]=1
results[1]=1
for i in range(2,n+1):
for j in range(0,i):
results[i] += results[j]*results[i-j-1]
return results[n]
153. Find Minimum in Rotated Sorted Array
題目鏈接:https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/
思路_(二分查找):
大概題意就是說當前的序列是一個有序的序列從某個節點打亂後的結果,比如[3,4,5,1,2] 要從這個序列中找到最小值。
看了別人的解題思路以後才懂了,利用二分查找(logn)
(1) A[mid] < A[end]:A[mid : end] sorted => min不在A[mid+1 : end]中
搜索A[start : mid]
(2) A[mid] > A[end]:A[start : mid] sorted且又因爲該情況下A[end]
class Solution(object):
def findMin(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
start, end = 0, len(nums)-1
target = nums[end]
while start<end:
mid = (start+end)/2
if nums[mid]<target:
end = mid
else:
start = mid+1
return min(nums[start],nums[end])
70. Climbing Stairs
題目鏈接:https://leetcode.com/problems/climbing-stairs/
思路_(DP):
題意:給定一個有n個臺階的梯子,每次可以走1步或者2步,問一共有多少種走法,典型的動態規劃問題,當前階梯數n的路徑數量=n-1階梯數的路徑數量+n-1階梯數的路徑數量
代碼:
class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
if n==1:
return 1
results = [0]*(n+1)
results[1] = 1
results[0] = 1
for i in range(2,n+1):
results[i] = results[i-1]+results[i-2]
return results[n]
Binary Tree Right Side View
題目鏈接:https://leetcode.com/problems/binary-tree-right-side-view/
思路:(queue層次遍歷):
題意:人站在樹的右邊,從右往左看,能看到的從上往下的序列。
做完這道題感覺智商被限制,debug了半天,對queue使用不熟練。
層次遍歷,每次先左右的節點入棧,遍歷每一層的時候把最右邊的節點值保存即可。
代碼:
class Solution(object):
def rightSideView(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
results = []
if root==None:
return []
queue = [root]
while queue:
for r in range(0,len(queue)):
cur = queue.pop(0)
if r==0:
results.append(cur.val)
if cur.right!=None:
queue.append(cur.right)
if cur.left!=None:
queue.append(cur.left)
return results
21. Merge Two Sorted Lists
題目鏈接:https://leetcode.com/problems/merge-two-sorted-lists/
思路_鏈表
鏈表合併沒啥難度上代碼:
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if l1==None:
return l2
if l2==None:
return l1
L = ListNode(0)
R = L
while l1 and l2:
if l1.val<l2.val:
L.next = l1
L = L.next
l1 = l1.next
else:
L.next = l2
L = L.next
l2 = l2.next
if l1==None:
L.next = l2
else:
L.next = l1
return R.next
Spiral Matrix II
題目鏈接:https://leetcode.com/problems/spiral-matrix-ii/
思路_螺旋矩陣生成
題意:給定一個數,將1·n^2以螺旋結構的形式填充到矩陣中。
代碼:
class Solution(object):
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
a = [[0]*n for x in range(n)]
colbegin,colend,rowbegin,rowend = 0,n,0,n
num = 1
while colbegin<colend and rowbegin<rowend:
if num<=n**2:
for i in range(colbegin,colend):
a[rowbegin][i] = num
num += 1
rowbegin += 1
if num<=n**2:
for i in range(rowbegin,rowend):
a[i][colend-1] = num
num += 1
colend -= 1
if num<=n**2:
for i in range(colend-1,colbegin-1,-1):
a[rowend-1][i] = num
num += 1
rowend -= 1
if num<=n**2:
for i in range(rowend-1,rowbegin-1,-1):
a[i][colbegin] = num
num += 1
colbegin += 1
return a