把只包含因子2、3和5的數稱作醜數(ugly number)。例如6、8都是醜數,但14不是,因為它包含因子7。 習慣上我們把1當做是第乙個醜數。求按從小到大的順序的第n個醜數。
# -*- coding:utf-8 -*-
class solution:
def getuglynumber_solution(self, index):
# write code here
if index <= 0:
return 0
res = [1]
t1 = t2 = t3 =0
nextindex = 1
while nextindex < index:
min_val = min(res[t1] * 2, res[t2] * 3, res[t3] * 5)
while res[t1] * 2 <= min_val:
t1 += 1
while res[t2] * 3 <= min_val:
t2 += 1
while res[t3] * 5 <= min_val:
t3 += 1
nextindex += 1
return res[index - 1]
在乙個字串(1<=字串長度<=10000,全部由字母組成)中找到第乙個只出現一次的字元,並返回它的位置。
# -*- coding:utf-8 -*-
class solution:
def firstnotrepeatingchar(self, s):
# write code here
if len(s) <= 0:
return -1
dict = {}
for i in s:
if i in dict:
dict[i] += 1
else:
dict[i] = 1
for index, val in enumerate(s):
if dict[val] == 1:
return index
return -1
請實現乙個函式用來找出字元流中第乙個只出現一次的字元。例如,當從字元流中只讀出前兩個字元"go"時,第乙個只出現一次的字元是"g"。當從該字元流中讀出前六個字元「google"時,第乙個只出現一次的字元是"l"。如果當前字元流沒有存在出現一次的字元,返回#字元。
# -*- coding:utf-8 -*-
class solution:
def __init__(self):
self.alist =
self.dict = {}
def insert(self, char):
if char in self.dict.keys():
self.dict[char] = 2
else:
self.dict[char] = 1
while len(self.alist) > 0 and self.dict[self.alist[0]] > 1:
self.alist.pop(0)
if len(self.alist) > 0:
return self.alist[0]
return '#"
在陣列中的兩個數字,如果前面乙個數字大於後面的數字,則這兩個數字組成乙個逆序對。輸入乙個陣列,求出這個陣列中的逆序對的總數p。並將p對1000000007取模的結果輸出。 即輸出p%1000000007
# -*- coding:utf-8 -*-
class solution:
def inversepairs(self, data):
# write code here
if len(data) <= 0:
return 0
copy =
count = 0
for i in range(len(data)):
i = 0
while len(copy) > i:
count += data.index(copy[i])
data.remove(copy[i])
i += 1
return count % 1000000007
輸入兩個鍊錶,找出它們的第乙個公共節點。
# -*- coding:utf-8 -*-
# class listnode:
# def __init__(self, x):
# self.val = x
# self.next = none
class solution:
def findfirstcommonnode(self, phead1, phead2):
# write code here
len1 = self.getlength(phead1)
len2 = self.getlength(phead2)
if len1 > len2:
plong = phead1
pshort = phead2
else:
plong = phead2
pshort = phead1
d = abs(len1 - len2)
for i in range(d):
plong = plong.next
whiel plong and pshort and plong != pshort:
plong = plong.next
pshort = pshort.next
return plong
def getlength(self, phead):
length = 0
while phead:
phead = phead.next
length += 1
return length
劍指offer 以空間換時間練習
1 題目要求 我們把只包含因子2 3 5的數稱作醜數,求按從小到大的順序的第1500個醜數。例如,6 8都是醜數,但14不是,因為它包含因子7.習慣上我們把1當做第乙個醜數。2 題目分析 方法一 首先,我們再來仔細分析一下醜數的概念,因為2,3,5是醜數的因子,那麼就可以說明任意乙個醜數對其中乙個因...
劍指offer讀書筆記 第五章,優化時間和空間效率
對於乙個陣列超過一半的數字就是眾數,直接摩爾投票方法,其他的方法都是渣渣。參考這個部落格找出陣列中出現次數超過一半的數 尋找眾數 摩爾投票法 這道題和求第k小的數的做法是一樣的,直接快排的思想去做即可。其實還可以使用堆來做 典型的動態規劃dp問題,直接做吧!參考這個鏈結leetcode 233.nu...
劍指offer 演算法 (時間空間效率的平衡)
題目描述 把只包含因子2 3和5的數稱作醜數 ugly number 例如6 8都是醜數,但14不是,因為它包含因子7。習慣上我們把1當做是第乙個醜數。求按從小到大的順序的第n個醜數。解析 根據醜數的定義,醜數應該是另乙個醜數乘以2 3或者5的結果 1除外 因此我們可以建立乙個陣列,裡面的數字是排好...