Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

找出数组中第二大的数(O(n)) #36

Open
Rain120 opened this issue Mar 29, 2022 · 0 comments
Open

找出数组中第二大的数(O(n)) #36

Rain120 opened this issue Mar 29, 2022 · 0 comments

Comments

@Rain120
Copy link
Owner

Rain120 commented Mar 29, 2022

function findSecondMax(arr) {
    let max = arr[0];
    let second = 0;

    for (let i = 1; i < arr.length; i++) {
        const item = arr[i];
        
        if (item > max) {
            second = max;
            max = item;
        }

        if (item > second && item < max) {
            second = item;
        }
    }

    return second;
}

// 9
findSecondMax([1, 2, 4, 10, 1, 6, 8, 7, 4, 2, 3, 9])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant