{ }codelper
最大・最小比較P0031

二番目に大きい数

一行目に整数の個数 n、二行目に n 個の整数が与えられる。
異なる値のうち二番目に大きい値を出力せよ。
同じ値が何度出ても一つと数える(5 5 3 なら答えは 3)。
異なる値が一つしかなければ "なし" を出力せよ。

入力
1 ≤ n ≤ 100、-1000 ≤ 各整数 ≤ 1000
出力
二番目に大きい値、または "なし"
例 1 · stdin
5
2 9 9 9 1
stdout
2
例 2 · stdin
3
4 4 4
stdout
なし
main.py
入力(stdin)

実行すると、これらの行が順に input()・標準入力に渡されます(実行中に入力を求めません)。

$ 準備完了

コードを入力して解くにはパソコンで開いてください。モバイルでは問題と解答を見られます。

ほかの言語では?言語別の解答を見る · 8 言語の解答

いちばん多い落とし穴は最大値が重なるときです。
並べ替えて後ろから二番目(sorted(a)[-2])を取ると 5 5 3 で 5 になります。
二つ目の落とし穴は初期値:0 から始めるとすべて負のとき間違えるので、最初の値(C なら INT_MIN)から始めます。
重なりの除き方:Python は最大値より小さいものだけ残して max、C# は Distinct().OrderByDescending()、C++ は std::set に入れて std::next(s.rbegin())。
C・Java は一度回りながら最大と二番目を一緒に更新します。
Craykon は それぞれ (x の中 a) で最大を見つけ、もう一度回って x < top のうち最大を探します。

Pythonmain.py · 5 行
n = int(input())a = list(map(int, input().split()))top = max(a)rest = [x for x in a if x < top]print(max(rest) if rest else "なし")
JavaScriptmain.js · 4 行
const [n, ...a] = require("fs").readFileSync(0, "utf8").trim().split(/\s+/).map(Number);const top = Math.max(...a);const rest = a.filter((x) => x < top);console.log(rest.length > 0 ? String(Math.max(...rest)) : "なし");
TypeScriptmain.ts · 5 行
import { readFileSync } from "node:fs";const [n, ...a]: number[] = readFileSync(0, "utf8").trim().split(/\s+/).map(Number);const top: number = Math.max(...a);const rest: number[] = a.filter((x) => x < top);console.log(rest.length > 0 ? String(Math.max(...rest)) : "なし");
JavaMain.java · 23 行
import java.util.Scanner; public class Main {    public static void main(String[] args) {        Scanner sc = new Scanner(System.in);        int n = sc.nextInt();        int first = sc.nextInt();        int second = 0;        boolean hasSecond = false;        for (int i = 1; i < n; i++) {            int x = sc.nextInt();            if (x > first) {                second = first;                hasSecond = true;                first = x;            } else if (x < first && (!hasSecond || x > second)) {                second = x;                hasSecond = true;            }        }        System.out.println(hasSecond ? String.valueOf(second) : "なし");    }}
C#Main.cs · 17 行
using System;using System.Linq; class Program{    static void Main()    {        Console.ReadLine();        var distinct = Console.ReadLine()            .Split(' ', StringSplitOptions.RemoveEmptyEntries)            .Select(int.Parse)            .Distinct()            .OrderByDescending(x => x)            .ToList();        Console.WriteLine(distinct.Count >= 2 ? distinct[1].ToString() : "なし");    }}
C++main.cpp · 15 行
#include <iostream>#include <iterator>#include <set> int main() {    int n, x;    std::cin >> n;    std::set<int> values;    for (int i = 0; i < n; i++) {        std::cin >> x;        values.insert(x);    }    if (values.size() < 2) std::cout << "なし\n";    else std::cout << *std::next(values.rbegin()) << "\n";}
Cmain.c · 20 行
#include <stdio.h> int main(void) {    int n, x, first, second = 0, has_second = 0;    scanf("%d %d", &n, &first);    for (int i = 1; i < n; i++) {        scanf("%d", &x);        if (x > first) {            second = first;            has_second = 1;            first = x;        } else if (x < first && (!has_second || x > second)) {            second = x;            has_second = 1;        }    }    if (has_second) printf("%d\n", second);    else puts("なし");    return 0;}
Craykonmain.cray · 25 行
n = コンソール.行読み().数に();a = コンソール.数読み();top = a[0];それぞれ (x の中 a){    top = 数学.大きい方(top, x);}found = 偽;second = 0;それぞれ (x の中 a){    もし (x < top && (!found || x > second))    {        second = x;        found = 真;    }}もし (found){    コンソール.書く(second);}でなければ{    コンソール.書く("なし");}