剑指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 

猜你喜欢

转载自blog.csdn.net/weixin_41813772/article/details/82656954
今日推荐