Rain120 / Web-Study

日常学习,工作写的笔记
66 stars 108 forks source link

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

Open Rain120 opened 2 years ago

Rain120 commented 2 years ago
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]);