优化时间和空间 python

题目:丑数

def get_ugly(n):
    ugly=[1]
    t2, t3, t5=0, 0, 0
    a=1
    while a<n:
        minum=min(ugly[t2]*2, ugly[t3]*3, ugly[t5]*5)
        ugly.append(minum)
        while ugly[t2]*2<=minum:
            t2+=1
        while ugly[t3]*3<=minum:
            t3+=1
        while ugly[t5]*5<=minum:
            t5+=1
        a+=1
    return ugly[-1]

题目:第一个只出现一次的字符

def first_not_repeat(s):
    dict={}
    for ele in s:
        dict[ele] = 1 if ele not in dict else dict[ele]+1
    for i in range(len(s)):
        if dict[s[i]] == 1:
            return i
    return -1

题目:两个链表第一个公共结点

def get_first_common_node(link1, link2):
    if not link1 or not link2:
        return None
    length1 = length2 = 0
    move1, move2 = link1, link2
    while move1:  # 获取链表长度
        length1 += 1
        move1 = move1.next
    while move2:
        length2 += 1
        move2 = move2.next
    while length1 > length2:  # 长链表先走多的长度
        length1 -= 1
        link1 = link1.next
    while length2 > length1:
        length2 -= 1
        link2 = link2.next
    while link1:  # 链表一起走
        if link1 == link2:
            return link1
        link1, link2 = link1.next, link2.next
    return None

题目:数组中超过了一半的数字

def get_more_half_num(nums):
    hashes=dict()
    length=len(nums)
    for n in nums:
        hashes[n] = hashes[n]+1 if hashes.get(n) else 1
        if hashes[n] > (length/2):
            return n

题目:最小的k个数

import heapq


def get_least_k_nums(nums, k):
    # 数组比较小的时候可以直接使用
    return heapq.nsmallest(k, nums)


class MaxHeap(object):
    def __init__(self, k):
        self.k = k
        self.data = []

    def push(self, elem):
        elem = -elem  # 入堆的时候取反,堆顶就是最大值的相反数了
        if len(self.data) < self.k:
            heapq.heappush(self.data, elem)
        else:
            least = self.data[0]
            if elem > least:
                heapq.heapreplace(self.data, elem)

    def get_least_k_nums(self):
        return sorted([-x for x in self.data])

题目:连续子数组最大和

def max_sum(nums):
    ret=0
    current=0
    for i in nums:
        if current<=0:
            current=i
        else:
            current+=i
        ret=max(current, ret)
    return ret

题目:把数组排成最小的数

class Solution:
    def theMax(self, str1, str2):
        '''定义字符串比较函数'''
        return str1 if str1+str2 > str2+str1 else str2

    def PrintMinNumber(self, numbers):
        """使用冒泡进行排序(把最大的放最后)"""
        string = [str(num) for num in numbers]
        res = []
        flag = True
        count = len(string) - 1
        while flag and  count > 0:
            flag = False
            for i in range(len(string)-1):
                if self.theMax(string[i], string[i+1]) == string[i]:
                    temp = string[i]
                    del string[i]
                    string.insert(i+1, temp)
                    flag = True
            count -= 1
        string = ''.join(string)
        return string

题目:1-n中出现1的次数

def get_digits(n):
    # 求整数n的位数
    ret = 0
    while n:
        ret += 1
        n /= 10
    return ret


def get_1_digits(n):
    """
    获取每个位数之间1的总数
    :param n: 位数
    """
    if n <= 0:
        return 0
    if n == 1:
        return 1
    current = 9 * get_1_digits(n-1) + 10 ** (n-1)
    return get_1_digits(n-1) + current


def get_1_nums(n):
    if n < 10:
        return 1 if n >= 1 else 0
    digit = get_digits(n)  # 位数
    low_nums = get_1_digits(digit-1)  # 最高位之前的1的个数
    high = int(str(n)[0])  # 最高位
    low = n - high * 10 ** (digit-1)  # 低位

    if high == 1:
        high_nums = low + 1  # 最高位上1的个数
        all_nums = high_nums
    else:
        high_nums = 10 ** (digit - 1)
        all_nums = high_nums + low_nums * (high - 1)  # 最高位大于1的话,统计每个多位数后面包含的1
    return low_nums + all_nums + get_1_nums(low)
发布了69 篇原创文章 · 获赞 2 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_42307828/article/details/85457000
今日推荐