lintcode刷題(Python)(3)__Python

來源:互聯網
上載者:User
友情提示,展開上面目錄以便查看具體題目。
排列序號 

給出一個不含重複數位排列,求這些數位所有排列按字典序排序後該排列的編號。其中,編號從1開始。 範例

例如,排列 [1,2,4] 是第 1 個排列。[2,1,4]是第3個排列

分析:這道題運用了階乘,數組長度為n,則共有n。種相片順序。

想要計算某個排列的序號,只要一個一個遍曆該排列,第一個數對應排序數組中的下標為i,則它的前面有i *(n-1)。種排列。然後再將該數pop出隊列,同時要把對應排序數組中的該數移出隊列。這樣遍曆下來,結果也就出來了。

class Solution:    # @param {int[]} A an integer array    # @return {long} a long integer    def permutationIndex(self, A):        # B是A的排序數組        B=sorted(A)        length=len(A)        if length==0:            return 0        result=1        for i in range(0,length):            result=result + B.index(A[0])* self.factor((length-1-i))            B.pop(B.index(A[0])) #要注意,B先要出隊列,A後出隊列。            A.pop(0)        return result    def factor(self,n):        result=1        for i in range(1,n+1):            result*=i        return result


簡化路徑 

給定一個文檔(Unix-style)的完全路徑,請進行路徑簡化。 範例

"/home/", => "/home"

"/a/./b/../../c/", => "/c"

這道題沒什麼難度,不過太細了,想像不到處理路徑都有這麼多情況。。

唯一要注意的就是處理“../”這種路徑,一旦出現這種形式,就意味著它前面的路徑要刪除掉。

我是用分割數組來處理的,先將路徑以“/../”為基準分割成兩部分,注意一定要分割一次。。

這樣我們就得到了一個含有兩個字串的數組,在第一個字串,我們再以“/”為基準對其進行分割,它的最後一個元素就是要被刪除的。

刪除完後,再把路徑拼起來,這樣迴圈處理,“../”就不存在了。

class Solution:    # @param {string} path the original path    # @return {string} the simplified path    def simplifyPath(self, path):        # Write your code here                           if "/./" in path:            path=path.replace("/./","/")        path=path.rstrip("/")         while "//" in path:            path=path.replace("//","/")        if "/..." not in path:            path=path.rstrip(".")        if path=="":            return "/"        while "/../" in path:            pathList=path.split("/../",1)            pathList0=pathList[0].split("/")            pathList0[len(pathList0)-1]=""            pathList[0]="/".join(pathList0)            path="".join(pathList)        return path


最大數 

給出一組非負整數,重新排列他們的順序把他們組成一個最大的整數。  注意事項

最後的結果可能很大,所以我們返回一個字串來代替這個整數。 您在真實的面試中是否遇到過這個題。  Yes 範例

給出 [1, 20, 23, 4, 8],返回組合最大的整數應為8423201。


這道題目真是精彩,想了好久,終於用自己的方法解出來了。

class Solution:    #@param num: A list of non negative integers    #@return: A string    def largestNumber(self, num):        # 對於[1, 20, 242,23, 4, 8],分成10組,每組找到最大長度的數(如,2中最大長度的數為242,長度為3)        # 對於長度不夠長的資料,將其補到最長長度,怎麼補這是有很大學問的。。        # 對於242、24222、24244這三個數,最大的結果肯定是2424424224222(312順序排列)        # 對於24、2423、2425、24144這四個數,最大的結果肯定是2425|24|2423|24144        # 補法:242補為24224,如果是24,則被為24242,怎麼看出來的呢。        # 先將所有的數補0補到同一長度,如24補為24000,2423補為24230,再找到最大的數(24250)        # 其他的數都以這個最大數為基準來被,如24補成24242,(如果補成6位的,就補成242425)        # 用一個列表存索引值對,鍵為num中的數字,值為補全之後的數字。對列表按值大小排序,        # 輸出鍵,即得到結果。        result=""        for x in range(0, 10):            i = 9 - x  #分別從0,1,2,3,4,6,7,8,9來遍曆            # 0開頭的數組,1開頭的數組。。。            listI = []            for j in num:                if str(j)[0] == str(i):                    listI.append(j)            if listI==[]:                continue            maxLength = len(str(max(listI, key=lambda c: len(str(c))))) #找到最大長度            # 補全0後的list            BuListI = []            for l in listI:                BuListI.append(l*(10**(maxLength-len(str(l)))))  #如l=15,補5位就是15000            BuMax=max(BuListI)  #找到了補全後最大的數            tupleList=[]            # 接下來開始補數,並以索引值對(元組)存到列表裡            for l in listI:                buPart=str(BuMax)[0:maxLength-len(str(l))+1]                AfterBu=int(str(l)+buPart)                tupleList.append((l,AfterBu))            tupleList.sort(key=lambda c:c[1],reverse=True)            for l in tupleList:                result=result+str(l[0])        result=result.lstrip("0")  #如輸入[0,0],則輸出不能為“00”        if result=="":            return "0"  #如輸入[0],不能輸出“”        return result


矩陣歸零

給定一個m×n矩陣,如果一個元素是0,則將其所在行和列全部元素變成0。

需要在原矩陣上完成操作。 範例

給出一個矩陣

[  [1, 2],  [0, 3]]

返回

[  [0, 2],  [0, 0]]

class Solution:    """    @param matrix: A list of lists of integers    @return: Nothing    """    def setZeroes(self, matrix):        # write your code here        # 一個列表中儲存座標為0的橫座標與縱座標        # 將矩陣中該置為0的置為0                if matrix==[]:            return []                lengthY=len(matrix)        lengthX=len(matrix[0])        zeroPositionY=[]        zeroPositionX=[]        for i in range(0,lengthY):            for j in range(0,lengthX):                if matrix[i][j]==0:                    zeroPositionY.append(i)                    zeroPositionX.append(j)        zeroPositionY=list(set(zeroPositionY))        zeroPositionX=list(set(zeroPositionX))        for i in zeroPositionY:            for j in range(0,lengthX):                matrix[i][j]=0        for j in zeroPositionX:            for i in range(0,lengthY):                matrix[i][j]=0


交錯正負數 

給出一個含有正整數和負整數的數組,重新排列成一個正負數交錯的數組。  注意事項

不需要保持正整數或者負整數原來的順序。 範例

給出數組[-1, -2, -3, 4, 5, 6],重新排序之後,變成[-1, 5, -2, 4, -3, 6]或者其他任何滿足要求的答案.

class Solution:    """    @param A: An integer array.    @return nothing    """    def rerange(self, A):        # 要考慮三種情況,一種是正數與負數數量相等,一種是正數比負數多一個,最後是負數比正數多一個。        # 先把正數與負數分開,儲存到兩個數組中。        # 針對三種情況,分別遍曆正數數組與負數數組,用pop方法不斷出棧即可。                A.sort()        minus=[]        positive=[]        for i in A:            if i<0:                minus.append(i)            else:                positive.append(i)        lengthA=len(A)        lenMinus=len(minus)        lenPositive=len(positive)        if lenMinus == lenPositive:            for i in range(0,lengthA,2):                    A[i]=minus[0]                    A[i+1]=positive[0]                    minus.pop(0)                    positive.pop(0)        if lenMinus>lenPositive:            count=0            A[count]=minus[0]            minus.pop(0)            count+=1            while count<lengthA:                A[count]=positive[0]                positive.pop(0)                count+=1                A[count] = minus[0]                minus.pop(0)                count+=1        if lenPositive>lenMinus:            count = 0            A[count] = positive[0]            positive.pop(0)            count += 1            while count < lengthA:                A[count] = minus[0]                minus.pop(0)                count += 1                A[count] = positive[0]                positive.pop(0)                count += 1

最長連續序列

給定一個未排序的整數數組,找出最長連續序列的長度。 說明   要求你的演算法複雜度為O(n) 範例

給出數組[100, 4, 200, 1, 3, 2],這個最長的連續序列是 [1, 2, 3, 4],返回所求長度 4

class Solution:    """    @param num, a list of integer    @return an integer    """    def longestConsecutive(self, num):        #先將num裡的元素去重,再排序。一個一個遍曆即可。        num = list(set(num))        maxLength=1        num.sort()        numCurrent=num[0]        length=len(num)        count=1        for i in range(1,length):            if num[i]-numCurrent==1:                numCurrent=num[i]                count+=1                maxLength=max(count,maxLength)            else:                numCurrent=num[i]                count=1        return maxLength


亂序字串 

給出一個字串數組S,找到其中所有的亂序字串(Anagram)。如果一個字串是亂序字串,那麼他存在一個字母集合相同,但順序不同的字串也在S中。  注意事項

所有的字串都只包含小寫字母
範例

對於字串數組 ["lint","intl","inlt","code"]

返回 ["lint","inlt","intl"]

class Solution:    # @param strs: A list of strings    # @return: A list of strings    def anagrams(self, strs):        # 將strs中的字串排序,放到另一個數組中。再統計每個字串出現的次數,如果次數大於1,        # 那麼肯定是有多個亂序字串存在了。再遍曆strs,找到這個字串對應的亂序字串,放到result裡面。        result = []        strsList = []        for str in strs:            strsList.append("".join(sorted(str)))        setStrsList = list(set(strsList))        for i in setStrsList:            if strsList.count(i)>1:                for str in strs:                    if sorted(str)==sorted(i):                        result.append(str)        return result

擺動排序 

給你一個沒有排序的數組,請將原數組就地重新排列滿足如下性質

nums[0] <= nums[1] >= nums[2] <= nums[3]....
 注意事項

請就地排序數組,也就是不需要額外數組 範例

給出數組為 nums = [3, 5, 2, 1, 6, 4] 一種輸出方案為 [1, 6, 2, 5, 3, 4]
這種有間隔的列表排列,一個很好的方法是先將列表分為兩部分,一部分是排序列表的前半部分,另一部分是排序列表的後半部分,這樣間隔遍曆前半部分與後半部分,就能達到題目的效果。 有一點要注意的是要分清列表的個數是奇數還是偶數,如果是偶數還好說,前半部分與後半部分的數量相等,如果是奇數,我預設前半部分比後半部分要多一個數字,因為題目中,列表中第一個是小數,所以此時最後一個肯定也是小數了,這樣前半部分必須比後半部分多出一個數來了。 代碼如下:

class Solution(object):    """    @param {int[]} nums a list of integer    @return nothing, modify nums in-place instead    """    def wiggleSort(self, nums):        nums.sort()        length=len(nums)        index=int((length+1)/2)        numsLeft=nums[0:index]        numsRight=nums[index:length]        for i in range(length):            if i %2==0:                nums[i]=numsLeft[0]                numsLeft.pop(0)            else:                nums[i]=numsRight[0]                numsRight.pop(0)        print(nums)


最小子串覆蓋 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.