Python程序从列表中查找N个最大元素

2021年3月20日17:21:38 发表评论 843 次浏览

给定一个整数列表, 任务是在列表的大小大于或等于o N的情况下找到N个最大元素。

例子 :

Input : [4, 5, 1, 2, 9] 
        N = 2
Output :  [9, 5]

Input : [81, 52, 45, 10, 3, 2, 96] 
        N = 3
Output : [81, 96, 52]

推荐:请尝试以下方法{IDE}首先, 在继续解决方案之前。

一个简单的解决方案遍历给定列表N次。在每次遍历中, 找到最大值, 将其添加到结果中, 然后将其从列表中删除。下面是实现:

# Python program to find N largest
# element from given list of integers
  
# Function returns N largest elements
def Nmaxelements(list1, N):
     final_list = []
  
     for i in range ( 0 , N): 
         max1 = 0
          
         for j in range ( len (list1)):     
             if list1[j] > max1:
                 max1 = list1[j];
                  
         list1.remove(max1);
         final_list.append(max1)
          
     print (final_list)
  
# Driver code
list1 = [ 2 , 6 , 41 , 85 , 0 , 3 , 7 , 6 , 10 ]
N = 2
  
# Calling the function
Nmaxelements(list1, N)

输出:

[85, 41]

时间复杂度:O(N * size)其中size是给定列表的大小。

方法2:

# Python program to find N largest
# element from given list of integers
  
l = [ 1000 , 298 , 3579 , 100 , 200 , - 45 , 900 ]
n = 4
  
l.sort()
print (l[ - n:])

输出如下:

[-45, 100, 200, 298, 900, 1000, 3579]
Find the N largest element: 4
[298, 900, 1000, 3579]

请参考数组中的k个最大(或最小)元素为这个问题提供更有效的解决方案。

注意怪胎!巩固你的基础Python编程基础课程和学习基础知识。

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: