1. 程式人生 > >劍指offer系列(十三)把陣列排成最小的數,醜數,把陣列排成最小的數

劍指offer系列(十三)把陣列排成最小的數,醜數,把陣列排成最小的數

把陣列排成最小的數

題目描述

輸入一個正整數陣列,把數組裡所有數字拼接起來排成一個數,列印能拼接出的所有數字中最小的一個。例如輸入陣列{3,32,321},則打印出這三個數字能排成的最小數字為321323。

解題思路:

把數字轉換為字串,然後cmp比較大小,升序排列後輸出。

cmp(x,y) 函式用於比較2個物件,如果 x < y 返回 -1, 如果 x == y 返回 0, 如果 x > y 返回 1

程式碼:

 map 與lambda關係參考:https://www.jianshu.com/p/07737690901e

# -*- coding:utf-8 -*-
#把陣列排成最小的數
class Solution:
    def PrintMinNumber(self, numbers):
        # write code here
        import operator
        if not numbers:
            return ''
        numbers = list(map(str, numbers))#轉為字串
        numbers.sort(cmp=lambda x,y: int(x+y)-int(y+x))#數字比較
        if numbers[0] == '0':
            return 0
        else:
            return ''.join(numbers)

醜數

題目描述

把只包含質因子2、3和5的數稱作醜數(Ugly Number)。例如6、8都是醜數,但14不是,因為它包含質因子7。 習慣上我們把1當做是第一個醜數。求按從小到大的順序的第N個醜數。

解題思路:

按順序把每個醜數放在陣列中,求下一個醜數。下一個醜數必定由有陣列中的某一個醜數A * 2, B * 3, C * 5 的中的最小值得來。
分析:在陣列中必定有一個醜數M2, 在它之前的數 * 2 都小於當前最大丑數, 在它之後的數 * 2都大於當前最大丑數,
同樣有M3, M5

程式碼:

# -*- coding:utf-8 -*-
class Solution:
    def GetUglyNumber_Solution(self, index):
        # write code here
        if index<1:
            return 0 
        res = [1]
        t2 = t3 = t5 = 0
        nextdex = 1
        while nextdex < index:
            minNum = min(res[t2]*2, res[t3]*3, res[t5]*5)
            res.append(minNum)
            #step步伐很小,每一個數都考慮到
            while res[t2]*2 <= minNum:
                t2 +=1
            while res[t3]*3<= minNum:
                t3 +=1
            while res[t5]*5 <= minNum:
                t5 +=1
                
            nextdex +=1
        return res[nextdex-1]

第一個只出現一次的字元

題目描述

在一個字串(0<=字串長度<=10000,全部由字母組成)中找到第一個只出現一次的字元,並返回它的位置, 如果沒有則返回 -1(需要區分大小寫).

解題思路:

先對每個字元出現的字元進行個數統計,然後再對原字串進行遍歷,找出第一個出現次數為1的字元

程式碼:

# -*- coding:utf-8 -*-
class Solution:
    def FirstNotRepeatingChar(self, s):
        # write code here
        from collections import Counter
        count = Counter(s)
        if not s:
            return -1
        for i,c in enumerate(s):
            if count[c] == 1:
                return i