学习编程语言的第一步几乎都是输出“Hello World”,而python也是如此。想要使用python语言输出"Hello World",需要使用python的heapq包中的heappush和heappop函数,heapq模块来实现最小堆,最小堆用于每次从所有列表的当前元素中选择最小的元素,再从最小堆中取出元素并合并。总体采用分治策略,将问题分解成更小的部分,递归地解决它们,然后将结果合并起来,这里输入是字符的嵌套列表,可以直接处理字符列表:

from heapq import heappush, heappop  
  
def mergeKLists(lists):  
    min_heap = []  
    for i, lst in enumerate(lists):  
        if lst:    
            heappush(min_heap, (lst[0], i, 0)) 
      
    merged = []  
    while min_heap:  
        val, list_ind, element_ind = heappop(min_heap)  
        merged.append(val)  
        if element_ind + 1 < len(lists[list_ind]):  
            next_tuple = (lists[list_ind][element_ind + 1], list_ind, element_ind + 1)  
            heappush(min_heap, next_tuple)    
      
    return merged  
#定义字符
a = "H"  
b = "e"  
c = "l"  
d = "o"  
e = "W"  
f = "r"  
g = "d" 
 
lists = [[a, b, c], [c, d, e], [d, f, c, g]]  

print(mergeKLists(lists)) 

  该方法的空间复杂度是 O(n + m),其中 n 是列表的数量,m 是所有列表中的元素总数。

  因为只需要输出字符串 ,所以可以简化代码,改用for循环的方式:

a = "H"  
b = "e"  
c = "l"  
d = "o"  
e = "W"  
f = "r"  
g = "d" 
k = [a, b, c, c, d, e, d, f, c, g]  

for i in range(1):  
    for j in range(len(k)):  
        print(k[j])

这段代码的时间复杂度是 O(n),空间复杂度是 O(1),感觉还是有点问题,所以需要进一步优化,可以将字符组合在一起,使其变成字符串,然后使用 split() 方法将字符串分割成单词列表,再使用 map() 和 lambda 函数将每个单词的首字母大写,最后使用 join() 方法将单词列表组合成一个字符串,并用空格分隔:

s = "hello world"    
words = s.split()    
capitalized_words = map(lambda x: x.capitalize(), words)   
capitalized_str = ' '.join(capitalized_words)  
print(capitalized_str) 

 这段代码的时间复杂度是 O(k),空间复杂度是 O(k * l),还可以使用join函数再优化以下:

chars = ['Hello', 'World']  
string = ' '.join(chars)  
print(string) 

这段代码的时间复杂度是 O(1),空间复杂度也是 O(1),这是突然有一个灵感,即使用格式化输出的方式,将"Hello"和"World"组合在一起输出:

char1 = 'Hello '  
char2 = 'World'   
string = f"{char1}{char2}"  
print(string) 

这时时间复杂度和空间复杂度已经汗流浃背了,因为还可以再次优化:

print("Hello World")

最后在大力优化下,可以直接使用print()函数直接输出字符串"Hello World",非常的使用,非常的简洁。

02-19 00:14