Given a list of integers, the task is to find N largest elements assuming size of list is greater than or equal o N. Examples :
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]
Recommended: Please try your approach on {IDE} first, before moving on to the solution.
A simple solution traverse the given list N times. In every traversal, find the maximum, add it to result, and remove it from the list. Below is the implementation :
Python3
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]
list1
=
[
2
,
6
,
41
,
85
,
0
,
3
,
7
,
6
,
10
]
N
=
2
Nmaxelements[list1, N]
Output :
[85, 41]
Time Complexity: O[N * size] where size is size of the given list.
Auxiliary space: O[N]
Method 2:
Python3
l
=
[
1000
,
298
,
3579
,
100
,
200
,
-
45
,
900
]
n
=
4
l.sort[]
print
[l[
-
n:]]
Output:
[-45, 100, 200, 298, 900, 1000, 3579] Find the N largest element: 4 [298, 900, 1000, 3579]
Time Complexity: O[nlogn]
Auxiliary Space: O[1]
Please refer k largest[or smallest] elements in an array for more efficient solutions of this problem.
Suppose we have an unsorted array, we have to find the kth largest element from that array. So if the array is [3,2,1,5,6,4] and k = 2, then the result will be 5.
To solve this, we will follow these steps −
- We will sort the element,
- if the k is 1, then return last element, otherwise return array[n – k], where n is the size of the array.
Let us see the following implementation to get better understanding −
Example
Live Demo
class Solution[object]: def findKthLargest[self, nums, k]: nums.sort[] if k ==1: return nums[-1] temp = 1 return nums[len[nums]-k] ob1 = Solution[] print[ob1.findKthLargest[[56,14,7,98,32,12,11,50,45,78,7,5,69], 5]]
Input
[56,14,7,98,32,12,11,50,45,78,7,5,69] 5
Output
50
Updated on 04-May-2020 09:00:26
- Related Questions & Answers
- Kth Largest Element in an Array
- Kth Largest Element in a Stream in Python
- Python Program to find largest element in an array
- Python Program to find the largest element in an array
- C++ Program to Find kth Largest Element in a Sequence
- Swap kth element of array - JavaScript
- Program to find largest element in an array in C++
- kth smallest/largest in a small range unsorted array in C++
- Kth Smallest Element in a BST in Python
- Python – Find Kth Even Element
- C++ Program to Find Largest Element of an Array
- Kth odd number in an array in C++
- Kth Smallest Element in a Sorted Matrix in Python
- Detecting the largest element in an array of Numbers [nested] in JavaScript
- Program to find kth missing positive number in an array in Python