在寫代碼的路上積少成多,現在都是最笨的方法實現要求,一點一點改進。
1. 替換空格
請實現一個函數,將一個字符串中的每個空格替換成“%20”。例如,當字符串爲We Are Happy.則經過替換之後的字符串爲We%20Are%20Happy。
分析:
①使用replace()
# -*- coding:utf-8 -*-
class Solution:
# s 源字符串
def replaceSpace(self, s):
# write code here
return s.replace(' ', '%20')
②使用split()和join()
# -*- coding:utf-8 -*-
class Solution:
# s 源字符串
def replaceSpace(self, s):
# write code here
return '%20'.join(s.split(' ') )
str = Solution()
string = 'We are a team'
string = str.replaceSpace(string)
print string
2.從頭到尾打印鏈表
輸入一個鏈表,按鏈表值從尾到頭的順序返回一個ArrayList。
分析
主要使用的函數是:list.reverse()
# -*- coding:utf-8 -*-
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# 返回從尾部到頭部的列表值序列,例如[1,2,3]
def printListFromTailToHead(self, listNode):
# write code here
m = []
head = listNode
while(head):
m.append(head.val)
head = head.next
m.reverse()
return m
3.二維數組查找
在一個二維數組中(每個一維數組的長度相同),每一行都按照從左到右遞增的順序排序,每一列都按照從上到下遞增的順序排序。請完成一個函數,輸入這樣的一個二維數組和一個整數,判斷數組中是否含有該整數。
分析:
會忽略的條件是列表爲空:[],[[]],特別是第二種情況,列表len([[]])=1的時候,還需要再判斷len(array[0])是不是也是空的。
# -*- coding:utf-8 -*-
class Solution:
# array 二維列表
def Find(self, target, array):
# write code here
count = 0
if array is not None:
for i in range(len(array)):
if len(array[0]) ==0:
return False
else:
for j in range(len(array[1])):
if target == array[i][j]:
count += 1
else:
return False
if count > 0:
return True
else:
return False
4.重建二叉樹
輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列{1,2,4,7,3,5,6,8}和中序遍歷序列{4,7,2,1,5,3,8,6},則重建二叉樹並返回。
分析:
遞歸思想,將先序和中序結合現將二叉樹的左右節點分開,然後再將左右作爲一個樹進行分解。
# -*- coding:utf-8 -*-
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# 返回構造的TreeNode根節點
def reConstructBinaryTree(self, pre, tin):
# write code here
#先序遍歷:遍歷順序規則爲【根左右】
#中序遍歷:遍歷順序規則爲【左根右】
#後序遍歷:遍歷順序規則爲【左右根】
if pre == []:
return None
val = pre[0]
ind = tin.index(val)
ltin = tin[0:ind]
rtin = tin[ind+1:]
lpre = pre[1:len(ltin)+1]
rpre = pre[len(ltin)+1:]
root = TreeNode(val)
root.left = self.reConstructBinaryTree(lpre, ltin)
root.right = self.reConstructBinaryTree(rpre, rtin)
return root
a = [1,2,4,7,3,5,6,8]
b = [4,7,2,1,5,3,8,6]
ll = Solution()
c = ll.reConstructBinaryTree(a, b)
[]和None是不一樣的。
pre = []
if pre is None:
print (True)
else:
print(False)
**False**
if pre == []:
print (True)
else:
print(False)
**True**
5.斐波那契數列
大家都知道斐波那契數列,現在要求輸入一個整數n,請你輸出斐波那契數列的第n項(從0開始,第0項爲0)。
n<=39
分析:
①笨辦法循環:
# -*- coding:utf-8 -*-
class Solution:
def Fibonacci(self, n):
# write code here
ret = []
ret.append(0)
ret.append(1)
ret.append(1)
for i in range(3, n+1):
ret.append(ret[i-1]+ ret[i-2])
return ret[n]
6.跳臺階
一隻青蛙一次可以跳上1級臺階,也可以跳上2級。求該青蛙跳上一個n級的臺階總共有多少種跳法(先後次序不同算不同的結果)。
分析:
假設一次跳一個臺階,那麼剩下的n-1個臺階就有f(n-1)種方法。
假設一次跳兩個臺階,那麼剩下的n-2個臺階就有f(n-1)種方法。
所以,n個臺階的跳法就有f(n-1)+f(n-2)種方法,是遞歸,所以可以參考菲波那切數列方法。
# -*- coding:utf-8 -*-
class Solution:
def jumpFloor(self, number):
# write code here
ret = []
ret.append(0)
ret.append(1)
ret.append(2)
for i in range(3, number+1):
ret.append(ret[i-1]+ret[i-2])
return ret[number]
7.變態跳臺階
一隻青蛙一次可以跳上1級臺階,也可以跳上2級……它也可以跳上n級。求該青蛙跳上一個n級的臺階總共有多少種跳法。
分析:
可以跳一級,二級,三級,…到n級,那麼跳上n級臺階可以記爲:
f(n) = f(n-1) + f(n-2) + f(n-3) + … + f(1) + f(0)
又
f(n-1) = f(n-2) + f(n-3) + f(n-3) + … + f(1) + f(0)
所以
f(n) = f(n-1) + f(n-1) = 2 * f(n-1)
# -*- coding:utf-8 -*-
class Solution:
def jumpFloorII(self, number):
# write code here
ret = []
ret.append(0)
ret.append(1)
for i in range(2, number+1):
ret.append(2*ret[i-1])
return ret[number]
8.旋轉數組的最小數字
把一個數組最開始的若干個元素搬到數組的末尾,我們稱之爲數組的旋轉。 輸入一個非減排序的數組的一個旋轉,輸出旋轉數組的最小元素。 例如數組{3,4,5,1,2}爲{1,2,3,4,5}的一個旋轉,該數組的最小值爲1。 NOTE:給出的所有元素都大於0,若數組大小爲0,請返回0。
分析:簡單的比較即可
# -*- coding:utf-8 -*-
class Solution:
def minNumberInRotateArray(self, rotateArray):
# write code here
if len(rotateArray) == 0:
return 0
if len(rotateArray) == 1:
return rotateArray
temp = []
for i in range(len(rotateArray)-1):
if rotateArray[i] > rotateArray[i+1]:
temp = rotateArray[i+1:]
temp = temp + rotateArray[:i+1]
rotateArray = temp
return rotateArray[0]
9.求1+2+3+…+n
分析:
①利用等差數列,公式求和sum=n*(n+1)/2.0
# -*- coding:utf-8 -*-
class Solution:
def Sum_Solution(self, n):
# write code here
sum = 0
sum = (1+n)*n/2.0
return sum
②遞歸
# -*- coding:utf-8 -*-
class Solution:
def Sum_Solution(self, n):
# write code here
if n == 1:
return 1
if n >= 2:
return n + self.Sum_Solution(n-1)
10.二進制中1的個數
輸入一個整數,輸出該數二進制表示中1的個數。其中負數用補碼錶示。
分析:
使用移位,按位與的方法進行比較,計算1的個數。
# -*- coding:utf-8 -*-
class Solution:
def NumberOf1(self, n):
# write code here
if n == 1:
return 1
count = 0
f1 = 1
for i in range(32):
if f1 & n :
count += 1
f1 = f1 << 1 #移位
return count
11.不用加減乘除做加法
寫一個函數,求兩個整數之和,要求在函數體內不得使用+、-、*、/四則運算符號。
分析:
遠程面試的時候,面試官問過這個問題,當時只回答出來了是按位運算和左移。
a+b = a^b + (a&b)<<1
①我用python做,在牛客上顯示複雜度過大?!在本地運行沒有問題,不解?!
class Solution:
def Add(self, num1, num2):
# write code here
sum1 = num1 ^ num2
temp = (num1 & num2)
while(temp != 0):
a = sum1
b = temp << 1
sum1 = a ^ b
temp = a & b
return sum1
②C++語言:(運行沒有問題)
class Solution {
public:
int Add(int num1, int num2)
{
int sum1;
int temp;
while(true)
{
sum1 = num1 ^ num2;
temp = (num1&num2) << 1;
num1 = sum1;
num2 = temp;
if (num2 == 0) break;
}
return sum1;
}
};
12.字符串的排列
輸入一個字符串,按字典序打印出該字符串中字符的所有排列。例如輸入字符串abc,則打印出由字符a,b,c所能排列出來的所有字符串abc,acb,bac,bca,cab和cba。
分析:
遞歸的思想,不斷縮小範圍。
①對所有的字符都要進行排序,包括重複的數組,開始的時候,我以爲不需要考慮重複的,後來編譯的時候會報錯。
②對所有字符排序結束後,要進行數組重複的排查,使用 set() 函數,會將重複數組剔除。
③最後使用 sorted() 實現整體數組按照大小的排序,例如:aab,aba, baa纔是正確的,aba, aab, baa是錯誤的;(!?不可思議!?)
# -*- coding:utf-8 -*-
class Solution:
def Permutation(self, ss):
# write code here
x = list(ss)
sl = []
if len(x) <= 1:
return x
sl = []
for i in range(len(x)):
for j in self.Permutation(x[:i]+x[i+1:]):
sl.append(x[i]+j)
sl = list(set(sl))
return sorted(sl) #特別重要,會對組合進行整體排序
13.數組中出現次數超過一半的數字
數組中有一個數字出現的次數超過數組長度的一半,請找出這個數字。例如輸入一個長度爲9的數組{1,2,3,2,2,2,5,4,2}。由於數字2在數組中出現了5次,超過數組長度的一半,因此輸出2。如果不存在則輸出0。
分析:
使用了字典去統計各個數字出現的次數,首先通過set()得到各個數字,然後通過循環得到數字出現的次數,使用了字典的形式,最後通過max()得到的次數最大對應的健值,最後,比較即可。
-*- coding:utf-8 -*-
class Solution:
def MoreThanHalfNum_Solution(self, numbers):
# write code here
x = set(numbers)
m = int(len(numbers)/2)
count = {}
for i in x:
count[i] = numbers.count(i)
l = max(count, key=count.get )
if count[l] > m:
return l
else:
return 0
14.數值的整數方次
給定一個double類型的浮點數base和int類型的整數exponent。求base的exponent次方。
分析:
將int型轉化爲浮點型即可
# -*- coding:utf-8 -*-
class Solution:
def Power(self, base, exponent):
# write code here
res = base ** float(exponent)
return res
15.調整數組順序使奇數位於偶數前面
輸入一個整數數組,實現一個函數來調整該數組中數字的順序,使得所有的奇數位於數組的前半部分,所有的偶數位於數組的後半部分,並保證奇數和奇數,偶數和偶數之間的相對位置不變。
分析:
將奇數和偶數分別放到兩個不同的list中,然後總結爲一個list。
偶數:n%2 == 0
# -*- coding:utf-8 -*-
class Solution:
def reOrderArray(self, array):
# write code here
even = []
odd = []
if array == []:
return []
if len(array)== 1:
return array
if len(array) > 1:
for i in range(len(array)):
if (array[i]%2) == 0:
even.append(array[i])
else:
odd.append(array[i])
return odd+even
16.矩形覆蓋
我們可以用21的小矩形橫着或者豎着去覆蓋更大的矩形。請問用n個21的小矩形無重疊地覆蓋一個2*n的大矩形,總共有多少種方法?
分析:
和臺階跳是一樣的問題,分治法,將問題分解,進行遞歸。
# -*- coding:utf-8 -*-
class Solution:
def rectCover(self, number):
# write code here
ret = []
ret.append(0)
ret.append(1)
ret.append(2)
for i in range(3, number+1):
ret.append(ret[i-1]+ret[i-2])
return ret[number]
17.數組中只出現一次的數字
一個整型數組裏除了兩個數字之外,其他的數字都出現了偶數次。請寫程序找出這兩個只出現一次的數字。
分析:
同數組中出現次數超過一半的數字。
# -*- coding:utf-8 -*-
class Solution:
# 返回[a,b] 其中ab是出現一次的兩個數字
def FindNumsAppearOnce(self, array):
# write code here
x = list(set(array))
count = {}
num = []
for i in x:
count[i] = array.count(i)
if count[i] == 1:
num.append(i)
return num
18.數組中重複的數字
在一個長度爲n的數組裏的所有數字都在0到n-1的範圍內。 數組中某些數字是重複的,但不知道有幾個數字是重複的。也不知道每個數字重複幾次。請找出數組中任意一個重複的數字。 例如,如果輸入長度爲7的數組{2,3,1,0,2,5,3},那麼對應的輸出是第一個重複的數字2。
分析:
同13,17,通過統計的方法得到數字出現的個數,然後輸出第一個重複的數字。
# -*- coding:utf-8 -*-
class Solution:
# 這裏要特別注意~找到任意重複的一個值並賦值到duplication[0]
# 函數返回True/False
def duplicate(self, numbers, duplication):
# write code here
count = {}
num = []
if len(numbers) <= 1:
return False
x = list(set(numbers))
for i in x:
count[i] = numbers.count(i)
if count[i] > 1:
num.append(i)
if len(num)>=1:
duplication[0] = num[0]
return True
else:
return False
19.最小K個數
輸入n個整數,找出其中最小的K個數。例如輸入4,5,1,6,2,7,3,8這8個數字,則最小的4個數字是1,2,3,4。
分析:
主要使用排序函數list.sort()或者sorted(list),然後取最小的K個數
# -*- coding:utf-8 -*-
class Solution:
def GetLeastNumbers_Solution(self, tinput, k):
# write code here
if len(tinput) < k:
return []
else:
tinput.sort()
return tinput[:k]
20.左旋轉字符串
彙編語言中有一種移位指令叫做循環左移(ROL),現在有個簡單的任務,就是用字符串模擬這個指令的運算結果。對於一個給定的字符序列S,請你把其循環左移K位後的序列輸出。例如,字符序列S=”abcXYZdef”,要求輸出循環左移3位後的結果,即“XYZdefabc”。是不是很簡單?OK,搞定它!
# -*- coding:utf-8 -*-
class Solution:
def LeftRotateString(self, s, n):
# write code here
return s[n:]+s[:n]
21.第一個只出現一次的字符
在一個字符串(0<=字符串長度<=10000,全部由字母組成)中找到第一個只出現一次的字符,並返回它的位置, 如果沒有則返回 -1(需要區分大小寫).
分析:
統計個數,然後輸出第一個字符,使用了list.index(x)
# -*- coding:utf-8 -*-
class Solution:
def FirstNotRepeatingChar(self, s):
# write code here
count={}
for i in s:
count[i] = s.count(i)
if count[i] == 1:
return s.index(i)
return -1
22.滑動窗口的最大值
給定一個數組和滑動窗口的大小,找出所有滑動窗口裏數值的最大值。例如,如果輸入數組{2,3,4,2,6,2,5,1}及滑動窗口的大小3,那麼一共存在6個滑動窗口,他們的最大值分別爲{4,4,6,6,6,5}; 針對數組{2,3,4,2,6,2,5,1}的滑動窗口有以下6個: {[2,3,4],2,6,2,5,1}, {2,[3,4,2],6,2,5,1}, {2,3,[4,2,6],2,5,1}, {2,3,4,[2,6,2],5,1}, {2,3,4,2,[6,2,5],1}, {2,3,4,2,6,[2,5,1]}。
分析:
主要是滑動窗口的個數計算,類似一維卷積,number = len(num)-size+1
# -*- coding:utf-8 -*-
class Solution:
def maxInWindows(self, num, size):
# write code here
number = len(num) - size + 1
b = []
if size == 0:
return []
else:
for i in range(number):
b.append(max(num[i:i+size]))
return b
23.把數組排成最小的數
輸入一個正整數數組,把數組裏所有數字拼接起來排成一個數,打印能拼接出的所有數字中最小的一個。例如輸入數組{3,32,321},則打印出這三個數字能排成的最小數字爲321323。
分析:
這道題我一直想要結合題12[字符串的排列],由於在函數**PrintMinNumber()這塊使用錯了遞歸,所以一直報錯,然後增加了子函數Permutation()**才編譯正確。【這部分大概出了10086+種編譯錯誤,要多思考】
需要注意的一點是:要將數組轉化爲string格式:numbers = list(map(str,numbers))
看見很多人分析了其他方法,我沒用,主要還是想結合遞歸來做(這種說法可能存在疑問?!)。
# -*- coding:utf-8 -*-
class Solution:
def Permutation(self, ss):
# write code here
x = list(ss)
sl = []
if len(x) <= 1:
return x
sl = []
for i in range(len(x)):
for j in self.Permutation(x[:i]+x[i+1:]):
sl.append(x[i]+j)
sl = list(set(sl))
return sorted(sl)
def PrintMinNumber(self, numbers):
# write code here
numbers = list(map(str,numbers))
if len(numbers) == 0:
return ""
else:
s = self.Permutation(numbers)
return s[0]
# return s[-1] 返回最大值
24.數組中的逆序對
在數組中的兩個數字,如果前面一個數字大於後面的數字,則這兩個數字組成一個逆序對。輸入一個數組,求出這個數組中的逆序對的總數P。並將P對1000000007取模的結果輸出。 即輸出P%1000000007
分析
法①:逐一比較【冒泡思想】,程序複雜度高,運行時間不合格
# -*- coding:utf-8 -*-
class Solution:
def InversePairs(self, data):
# write code here
count = 0
if len(data) <= 1:
return 0
else:
for i in range(len(data)):
m = data[i]
for j in data[i+1:]:
if m > j:
count += 1
return count%1000000007
法②:排序,索引變換
運行提示時間複雜度大
class Solution:
def InversePairs(self, data):
count = 0
copy = sorted(data)
for i in range(len(copy)):
count += data.index(copy[i])
data.remove(copy[i])
return count
法③:歸併排序,減少時間複雜度【現在不會,保留】
25.和爲S的兩個數字
輸入一個遞增排序的數組和一個數字S,在數組中查找兩個數,使得他們的和正好是S,如果有多對數字的和等於S,輸出兩個數的乘積最小的。
分析:
已知一個數求另外一個數是否在這個數組中即可。
法①:數組不是遞增排序,而是無重複的無序數組
# -*- coding:utf-8 -*-
class Solution:
def FindNumbersWithSum(self, array, tsum):
# write code her
mul = []
m = []
d = []
if array == []:
return []
else:
for i in range(len(array)):
y = tsum - array[i]
if y in array[i+1:]:
mul.append(y*array[i])
m.append(y)
if mul == []:
return []
else:
a = min(mul)
b = mul.index(a)
c = tsum - m[b]
d.append(m[b])
d.append(c)
return sorted(d)
法②
# -*- coding:utf-8 -*-
class Solution:
def FindNumbersWithSum(self, array, tsum):
# write code her
mul = []
m = []
if array == []:
return []
else:
for i in range(len(array)):
y = tsum - array[i]
if y in array[i+1:]:
mul.append(y*array[i])
m.append([array[i], y])
if mul:
return m[0]
else:
return mul
26.數字在排序數列中出現的次數
統計一個數字在排序數組中出現的次數。
# -*- coding:utf-8 -*-
class Solution:
def GetNumberOfK(self, data, k):
# write code here
count = {}
if k in data:
return data.count(k)
else:
return 0
或者直接:
return data.count(k)
27.把字符串轉化爲整數
將一個字符串轉換成一個整數(實現Integer.valueOf(string)的功能,但是string不符合數字要求時返回0),要求不能使用字符串轉換整數的庫函數。 數值爲0或者字符串不是一個合法的數值則返回0。
分析:
編譯成功83.33%,沒找到問題在哪?:問題在當輸入爲’+'時,不能執行是s[1:]
所以增加了當len(s)=1時的判斷。
# -*- coding:utf-8 -*-
class Solution:
def StrToInt(self, s):
if not s:
return 0
mul = 1
res = 0
flag = 1
if len(s) == 1:
if '9'>= s[0] >= '0':
return (ord(s)-ord('0'))
else:
return 0
else:
if s[0] == '+':
flag = 1
s = s[1:]
if s[0] == '-':
flag = -1
s = s[1:]
for i in range(len(s)-1, -1, -1):
if '9'>= s[i] >= '0':
res += (ord(s[i])-ord('0')) * mul
mul = mul * 10
else:
res = 0
break
return res * flag if res else 0
28.數據流中的中位數
如何得到一個數據流中的中位數?如果從數據流中讀出奇數個數值,那麼中位數就是所有數值排序之後位於中間的數值。如果從數據流中讀出偶數個數值,那麼中位數就是所有數值排序之後中間兩個數的平均值。我們使用Insert()方法讀取數據流,使用GetMedian()方法獲取當前讀取數據的中位數。
分析:
一直沒明白數據流是什麼意思,現在清楚了。當不斷的輸入數據時,要求姐當前數據中的中位數。所以使用Insert()表示不斷增加數據,GetMedian()用來計算當前數據集的中位數:先排序後取中位數。
# -*- coding:utf-8 -*-
class Solution:
def __init__(self):
self.nums = []
def Insert(self, num):
self.nums.append(num)
# write code here
def GetMedian(self, k):
# write code here
self.nums.sort()
if len(self.nums) % 2 == 0:
return (self.nums[len(self.nums)/2]+self.nums[len(self.nums)/2-1])/2.0
else:
return self.nums[(len(self.nums)-1)/2]
29.把二叉樹多行打印
從上到下按層打印二叉樹,同一層結點從左至右輸出。每一層輸出一行。
分析:
需要理解怎麼建立的二叉樹
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回二維列表[[1,2],[4,5]]
def Print(self, pRoot):
A = []
res = []
if not pRoot:
return res
A.append(pRoot)
while A:
temp = []
for Node in A:
temp.append(Node.val)
size = len(A)
res.append(temp)
for i in range(size):
current_root = A.pop(0)
if current_root.left:
A.append(current_root.left)
if current_root.right:
A.append(current_root.right)
return res
30.二叉樹的深度
輸入一棵二叉樹,求該樹的深度。從根結點到葉結點依次經過的結點(含根、葉結點)形成樹的一條路徑,最長路徑的長度爲樹的深度。
分析:
法①:
與題29結合,直接計算打印行數的len()
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def TreeDepth(self, pRoot):
# write code here
A = []
res = []
if not pRoot:
return 0
A.append(pRoot)
while A:
temp = []
for Node in A:
temp.append(Node.val)
size = len(A)
res.append(temp)
for i in range(size):
current_root = A.pop(0)
if current_root.left:
A.append(current_root.left)
if current_root.right:
A.append(current_root.right)
return len(res)
法②:
class Solution:
def TreeDepth(self, pRoot):
# write code here
A = []
if not pRoot:
return 0
A.append(pRoot)
num = 0
while A:
size = len(A)
for i in range(size):
current_root = A.pop(0)
if current_root.left:
A.append(current_root.left)
if current_root.right:
A.append(current_root.right)
num = num + 1
return num
法③:通過遞歸函數進行計算
class Solution:
def TreeDepth(self, pRoot):
# write code here
if not pRoot:
return 0
else:
left = self.TreeDepth(pRoot.left)
right = self.TreeDepth(pRoot.right)
return max(left, right)+1
31.二叉樹的鏡像
操作給定的二叉樹,將其變換爲源二叉樹的鏡像。
分析:
遞歸真的太好了,太好了
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回鏡像樹的根節點
def Mirror(self, root):
# write code here
if not root:
return None
root.left, root.right = root.right, root.left
if root.left:
self.Mirror(root.left)
if root.right:
self.Mirror(root.right)
32.連續數組的最大和
HZ偶爾會拿些專業問題來忽悠那些非計算機專業的同學。今天測試組開完會後,他又發話了:在古老的一維模式識別中,常常需要計算連續子向量的最大和,當向量全爲正數的時候,問題很好解決。但是,如果向量中包含負數,是否應該包含某個負數,並期望旁邊的正數會彌補它呢?例如:{6,-3,-2,7,-15,1,2,2},連續子向量的最大和爲8(從第0個開始,到第3個爲止)。給一個數組,返回它的最大連續子序列的和,你會不會被他忽悠住?(子向量的長度至少是1)
分析:
計算全部連續數組的和,然後取最大值。
class Solution:
def FindGreatestSumOfSubArray(self, array):
# write code here
b = []
if array == []:
return None
if len(array) == 1:
return b.append(array)
for i in range(len(array)-2):
sum = array[i]
a = []
a.append(sum)
for j in array[i+1:]:
sum += j
a.append(sum)
b.append(max(a))
return max(b)
33.翻轉單詞順序列
牛客最近來了一個新員工Fish,每天早晨總是會拿着一本英文雜誌,寫些句子在本子上。同事Cat對Fish寫的內容頗感興趣,有一天他向Fish借來翻看,但卻讀不懂它的意思。例如,“student. a am I”。後來才意識到,這傢伙原來把句子單詞的順序翻轉了,正確的句子應該是“I am a student.”。Cat對一一的翻轉這些單詞順序可不在行,你能幫助他麼?
分析:
同題1
class Solution:
def ReverseSentence(self, s):
# write code here
if not s:
return ""
b = s.split(' ')
b.reverse()
return ' '.join(b)
34.整數中1出現的次數
求出113的整數中1出現的次數,並算出1001300的整數中1出現的次數?爲此他特別數了一下1~13中包含1的數字有1、10、11、12、13因此共出現6次,但是對於後面問題他就沒轍了。ACMer希望你們幫幫他,並把問題更加普遍化,可以很快的求出任意非負整數區間中1出現的次數(從1 到 n 中1出現的次數)。
分析:
統計list中含‘1’的個數
# -*- coding:utf-8 -*-
class Solution:
def NumberOf1Between1AndN_Solution(self, n):
# write code here
sum = 0
for i in range(1, n+1):
a = str(i)
b = list(a)
c = b.count('1')
sum += c
return sum
35.從上往下打印二叉樹
從上往下打印出二叉樹的每個節點,同層節點從左至右打印。
分析:
同29從上到下打印二叉樹
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回從上到下每個節點值列表,例:[1,2,3]
def PrintFromTopToBottom(self, root):
# write code here
A = []
res = []
if not root:
return res
A.append(root)
while A:
for Node in A:
res.append(Node.val)
size = len(A)
for i in range(size):
current_root = A.pop(0)
if current_root.left:
A.append(current_root.left)
if current_root.right:
A.append(current_root.right)
return res
36.二叉搜索樹的後序遍歷
輸入一個整數數組,判斷該數組是不是某二叉搜索樹的後序遍歷的結果。如果是則輸出Yes,否則輸出No。假設輸入的數組的任意兩個數字都互不相同。
分析:
遞歸函數
二叉搜索樹:二叉查找樹(Binary Search Tree),(又:二叉搜索樹,二叉排序樹)它或者是一棵空樹,或者是具有下列性質的二叉樹: 若它的左子樹不空,則左子樹上所有結點的值均小於它的根結點的值; 若它的右子樹不空,則右子樹上所有結點的值均大於它的根結點的值; 它的左、右子樹也分別爲二叉排序樹。
class Solution:
def VerifySquenceOfBST(self, sequence):
# write code here
if sequence is None:
return False
if len(sequence) == 0:
return False
n = len(sequence)
root = sequence[-1]
for i in range(n):
if sequence[i] > root:
break
for j in range(i, n):
if sequence[j] < root:
return False
left = True
if i > 0:
left = self.VerifySquenceOfBST(sequence[0:i])
right = True
if i < n-1:
right = self.VerifySquenceOfBST(sequence[i:-1])
return left and right