目录

AtCoder B 213

AtCoder

tyz020 | 08 Aug 2021

题目大意

题目给了一个数组,要求找到第二大的数值,并返回其在输入数组内的索引

解题思路

将分值以及索引存储至对象并放入数组内

将数组按分值从大到小排序

输出排序完的数组里第二个分值

复杂度

将所有分值存储至数组内, \(O(N)\) 将数组排序, \(O(N\log{N})\) 因此,最终复杂度为 \(O(N\log{N})\)

提交代码

import java.util.*;
import java.io.*;

public class Main{
  static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  static String[] input;
  
  public static void main(String[] args) throws IOException {
    parseInput();
    Player[] players = new Player[input.length];
    for(int i = 0; i < input.length; i++) players[i] = new Player(i + 1, Integer.parseInt(input[i]));
    Arrays.sort(players);
    System.out.println(players[1].index);
  }
  
  public static void parseInput() throws IOException {
    br.readLine();
    input = br.readLine().split(" ");
  }
}

class Player implements Comparable<Player> {
  int index, score;
  
  public Player(int index, int score) {
    this.index = index;
    this.score = score;
  }
  
  public int compareTo(Player other) {
    if(this.score < other.score) return 1;
    else if(this.score > other.score) return -1;
    else return 0;
  }
  
  public String toString() {
    return this.index + ", " + this.score;
  }
}

评论区