📜  使用PHP编写程序以获取数组中第二高的数字?

📅  最后修改于: 2022-05-13 01:56:21.152000             🧑  作者: Mango

使用PHP编写程序以获取数组中第二高的数字?

给定一个整数数组,任务是编写一个程序来有效地找到数组中存在的第二大元素。

例子:

Input: arr[] = {13, 14, 15, 16, 17, 18}
Output: The second largest element is 17.
Explanation: The largest element of the array
is 35 and the second largest element is 17

Input: arr[] = {10, 5, 10}
Output: The second largest element is 5.
Explanation: The largest element of the array
is 10 and the second largest element is 5

Input: arr[] = {10, 10, 10}
Output: The second largest does not exist.
Explanation: Largest element of the array  
is 10 there is no second largest element

简单的解决方案:

方法:想法是对数组进行降序排序,然后从排序后的数组中返回不等于最大元素的第二个元素。

PHP


PHP
 $first) {
            $second = $first;
            $first = $arr[$i];
        }
  
        // If arr[i] is in
        // between first and
        // second then update
        // second
        else if ($arr[$i] > $second &&
                $arr[$i] != $first)
            $second = $arr[$i];
    }
    if ($second == PHP_INT_MIN)
        echo("There is no second largest element\n");
    else
        echo("The second largest element is "
                 . $second . "\n");
}
  
// Driver Code
$arr = array(12, 35, 1, 10, 34, 1);
$n = sizeof($arr);
print2largest($arr, $n);
  
?>



输出
Second Largest element is 64

复杂性分析:

另一种方法:在一次遍历中找到第二大元素。

以下是执行此操作的完整算法:

1) Initialize the first as 0 (i.e, index of arr[0] element)
2) Start traversing the array from array[1],
  a) If the current element in array say arr[i] is greater
     than first. Then update first and second as,
     second = first
     first = arr[i]
  b) If the current element is in between first and second,
     then update second to store the value of current variable as
     second = arr[i]
3) Return the value stored in second.

PHP

 $first) {
            $second = $first;
            $first = $arr[$i];
        }
  
        // If arr[i] is in
        // between first and
        // second then update
        // second
        else if ($arr[$i] > $second &&
                $arr[$i] != $first)
            $second = $arr[$i];
    }
    if ($second == PHP_INT_MIN)
        echo("There is no second largest element\n");
    else
        echo("The second largest element is "
                 . $second . "\n");
}
  
// Driver Code
$arr = array(12, 35, 1, 10, 34, 1);
$n = sizeof($arr);
print2largest($arr, $n);
  
?>
输出
The second largest element is 34