当前位置: 面试刷题>> 第2章提高200例 (经典算法题500道)


由于原题目描述不完整,我将假设一个常见的算法题场景来补全题目,并给出PHP、Python、JavaScript三种语言的示例代码。这个假设的场景是“寻找数组中的第二大元素”。

题目描述

给定一个非空整数数组,编写一个函数来查找其中第二大的元素。注意,数组中可能包含重复的元素。

示例

输入: [1, 2, 3, 4, 3]
输出: 3

输入: [1, 2]
输出: 1
(如果数组中没有第二大的元素,则返回数组中最大的元素)

PHP 示例代码

function findSecondLargest($nums) {
    $firstMax = PHP_INT_MIN;
    $secondMax = PHP_INT_MIN;
    
    foreach ($nums as $num) {
        if ($num > $firstMax) {
            $secondMax = $firstMax;
            $firstMax = $num;
        } elseif ($num > $secondMax && $num !== $firstMax) {
            $secondMax = $num;
        }
    }
    
    // 如果没有第二大的元素,返回最大的元素
    return $firstMax == $secondMax ? $firstMax : $secondMax;
}

// 测试
echo findSecondLargest([1, 2, 3, 4, 3]); // 输出 3
echo "\n";
echo findSecondLargest([1, 2]); // 输出 1

Python 示例代码

def find_second_largest(nums):
    first_max = float('-inf')
    second_max = float('-inf')
    
    for num in nums:
        if num > first_max:
            second_max, first_max = first_max, num
        elif first_max > num > second_max:
            second_max = num
    
    # 如果没有第二大的元素,返回最大的元素
    return second_max if second_max != float('-inf') else first_max

# 测试
print(find_second_largest([1, 2, 3, 4, 3]))  # 输出 3
print(find_second_largest([1, 2]))  # 输出 1

JavaScript 示例代码

function findSecondLargest(nums) {
    let firstMax = -Infinity;
    let secondMax = -Infinity;
    
    for (let num of nums) {
        if (num > firstMax) {
            [secondMax, firstMax] = [firstMax, num];
        } else if (num < firstMax && num > secondMax) {
            secondMax = num;
        }
    }
    
    // 如果没有第二大的元素,返回最大的元素
    return secondMax === -Infinity ? firstMax : secondMax;
}

// 测试
console.log(findSecondLargest([1, 2, 3, 4, 3])); // 输出 3
console.log(findSecondLargest([1, 2])); // 输出 1

码小课

码小课网站中有更多关于算法和数据结构的精彩内容,涵盖了从基础到进阶的各类问题,欢迎大家前往学习,不断提升自己的编程技能。