📅  最后修改于: 2023-12-03 14:46:03.672000             🧑  作者: Mango
In Python, it is very easy to find the second maximum element in a list. Here we are going to discuss some methods to find the second maximum element in a list.
def find_second_maximum(arr):
sorted_arr = sorted(arr, reverse=True)
return sorted_arr[1] if len(sorted_arr) > 1 else None
This method uses the sorted() function to sort the array in descending order and returns the second element of that sorted array. If the array contains only one element, then it returns None.
def find_second_maximum(arr):
max_elem = max(arr)
arr.remove(max_elem)
return max(arr) if arr else None
This method first finds the maximum element in the array using the max() function. After that, it removes the maximum element from the array and returns the maximum element again, which is now the second maximum element. If the array is empty after removing the maximum element, then it returns None.
def find_second_maximum(arr):
max_elem = arr[0]
sec_max = None
for elem in arr[1:]:
if elem > max_elem:
sec_max = max_elem
max_elem = elem
elif sec_max is None or elem > sec_max:
sec_max = elem
return sec_max
This method iterates through the array and keeps track of the maximum and second maximum elements. It returns the second maximum element.
Choose the method that suits your code and requirement.