I made a method that tries to find the second largest number in an unsorted list of integers with pointers. When I pass any list of integers that has the second largest number placed side by side before the largest number, I dont get the expected results. For example, when I pass [2, 6, 6, 2, 11]
, I get as output:
Largest: 11
Second Largest: 2
The 6
is never assigned to the second_max
because of this line:
elif j > second_max and first_max != j:
If I remove the second condition, the method can potentially assign duplicates to first_max
and second_max
and not output the actual second largest number.
first_max=float('-inf')
second_max=float('-inf')
for i,j in enumerate(nums):
if j > first_max:
first_max=j
elif j > second_max and first_max != j:
second_max=j
if first_max == float('-inf'):
first_max,second_max=None,None
elif second_max == float('-inf'):
second_max=None
print("Largest: {}".format(first_max))
print("Second Largest: {}".format(second_max))
Would appreciate any help on this.
EDIT: I know there's a similar post to this but it does not answer my question of dealing with duplicates. I want the method to evaluate duplicates as one number only.
The output for this [5,5,4,2] and [2, 6, 6, 2, 11] as inputs should be respectively:
Largest: 5 Second Largest: 4
Largest: 11 Second Largest: 6