問題の説明:
総計 n 個のチームが存在し、0 から n - 1 までの番号が割り当てられています。
0から始まる n × n の二次元ブール行列 grid が与えられます。0 <= i, j <= n - 1 かつ i != j となるすべての i, j について、もし grid[i][j] == 1 であれば、チーム i はチーム j よりも強いとします。そうでなければ、チーム j はチーム i よりも強いとします。
このコンペティションにおいて、チーム a よりも強力なチームが存在しない場合、チーム a は 優勝チーム となります。
このコンペティションで優勝チームとなるチームの番号を返してください。
例1:
<strong>入力:</strong>grid = [[0,1],[0,0]]
<strong>出力:</strong>0
<strong>説明:</strong>2つのチームがあります。
grid[0][1] == 1 はチーム0がチーム1より強いことを意味します。したがって、チーム0が優勝です。
例2:
<strong>入力:</strong>grid = [[0,0,1],[1,0,1],[0,0,0]]
<strong>出力:</strong>1
<strong>説明:</strong>3つのチームがあります。
grid[1][0] == 1 はチーム1がチーム0より強いことを意味します。
grid[1][2] == 1 はチーム1がチーム2より強いことを意味します。
したがって、チーム1が優勝です。
制約:
n == grid.lengthn == grid[i].length2 <= n <= 100grid[i][j]の値は0または1- 全ての
iについて、grid[i][i]は0です。 i != jである全てのi, jについて、grid[i][j] != grid[j][i]が成り立ちます。- 与えられる入力は以下の条件を満たします:もしチーム
aがチームbより強く、チームbがチームcより強いならば、チームaはチームcよりも強いです。
解法
import java.util.Arrays;
import java.util.Scanner;
/**
* @author: hj
* @className: Solution42
* @Describe:LeeCode 2923 優勝チームの特定
*/
public class Solution42 {
public static void main(String[] args) {
// 配列のサイズは任意に設定可能
int[][] teams = new int[2][2];
int temp = 0;
Scanner scan = new Scanner(System.in);
for (int i = 0; i < teams.length; i++){
for (int j = 0; j < teams[i].length; j++){
temp = scan.nextInt();
teams[i][j] = temp;
}
}
int champion = findChampion3(teams);
System.out.println(champion);
}
/**
* @Description 解法1 バリューチェックとカウンター
* @author hj
* @date 2024/4/12 13:21
* @param grid
*
*/
public static int findChampion(int[][] grid){
int[] scores = new int[grid.length];
Arrays.fill(scores, 0);
for (int i = 0 ; i < grid.length; i++){
for (int j = 0; j < grid[i].length; j++){
if (grid[i][j] == 1){
scores[i]++;
}
}
}
int maxScore = scores[0];
int winnerIndex = 0;
int previousMax = maxScore;
for (int i = 1 ; i < scores.length; i++){
maxScore = Math.max(maxScore,scores[i]);
if (previousMax != maxScore){
winnerIndex = i;
previousMax = maxScore;
}
}
return winnerIndex;
}
/**
* @Description 解法2 チームツリーの考え方を応用
* @author hj
* @date 2024/4/12 13:21
* @param grid
*
*/
public static int findChampion2(int[][] grid){
int currentWinner = 0;
int totalTeams = grid.length;
for (int i = 0; i < totalTeams; i++){
if (grid[i][currentWinner] != 0){
currentWinner = i;
}
}
return currentWinner;
}
/**
* @Description 解法3 合計スコア比較
* @author hj
* @date 2024/4/12 13:29
* @param null
*
*/
public static int findChampion3(int[][] grid){
int winnerIndex = 0; // 最高スコアチーム
int totalTeams = grid.length;
int[] teamScores = new int[totalTeams];
Arrays.fill(teamScores, 0);
for (int i = 0; i < totalTeams; i++){
for (int score : grid[i]){
teamScores[i] += score;
}
}
for (int i = 0; i < totalTeams; i++){
System.out.print(teamScores[i] + "\t");
}
System.out.println();
int highestScore = teamScores[0]; // 最高スコア
for(int i = 1; i < teamScores.length; i++){
if (highestScore < teamScores[i]){
highestScore = teamScores[i];
winnerIndex = i;
}
}
return winnerIndex;
}
}