Last active
November 21, 2022 22:24
-
-
Save samsonq/520d146917b5a9bd2bf572ca6887fff6 to your computer and use it in GitHub Desktop.
Second Largest O(n)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def second_largest(n): | |
first = n[0] | |
second = n[1] | |
if second > first: | |
first, second = second, first | |
for i in range(2, len(n)): | |
if n[i] > first: | |
first, second = n[i], first | |
if second > first: | |
first, second = second, first | |
elif (n[i] > second) and (n[i] < first): | |
second = n[i] | |
return second | |
x = [1, 2, 3, 4, 10, 9, 8, 7, 6, 5] | |
print(second_largest(x)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment