[LeetCode] Count of Matches in Tournament

준규·2022년 12월 24일

1.문제


You are given an integer n, the number of teams in a tournament that has strange rules:

  • If the current number of teams is even, each team gets paired with another team. A total of n / 2 matches are played, and n / 2 teams advance to the next round.
  • If the current number of teams is odd, one team randomly advances in the tournament, and the rest gets paired. A total of (n - 1) / 2 matches are played, and (n - 1) / 2 + 1 teams advance to the next round.

Return the number of matches played in the tournament until a winner is decided.


정수 n이 주어질 때 현재 남아있는 teams의 수에 따라 아래의 다른 룰을 적용하여 토너먼트를 진행한다고 한다.

  • 현재 팀의 개수가 짝수라면 팀의 절반은 다음 토너먼트로 진출한다. 이때 이뤄지는 경기의 수는 n / 2 이다.
  • 현재 팀의 개수가 홀수라면 (n-1) / 2 + 1 의 팀이 다음 토너먼트에 진출하고 이때 이뤄지는 경기의 수는 (n - 1) / 2 이다.

승자 팀이 결정되기까지의 토너먼트 경기수의 총합을 리턴하는 문제이다.


Example 1

Input: n = 7
Output: 6
Explanation: Details of the tournament: 
- 1st Round: Teams = 7, Matches = 3, and 4 teams advance.
- 2nd Round: Teams = 4, Matches = 2, and 2 teams advance.
- 3rd Round: Teams = 2, Matches = 1, and 1 team is declared the winner.
Total number of matches = 3 + 2 + 1 = 6.

Example 2

Input: n = 14
Output: 13
Explanation: Details of the tournament:
- 1st Round: Teams = 14, Matches = 7, and 7 teams advance.
- 2nd Round: Teams = 7, Matches = 3, and 4 teams advance.
- 3rd Round: Teams = 4, Matches = 2, and 2 teams advance.
- 4th Round: Teams = 2, Matches = 1, and 1 team is declared the winner.
Total number of matches = 7 + 3 + 2 + 1 = 13.

Constraints:

  • 1 <= n <= 200

2.풀이

  1. 현재 팀이 짝수인지 홀수인지에따라 while문을 돌 때 체크를 한다.
  2. 짝수, 홀수에 맞는 룰을 적용해서 새로운 team의 갯수를 갱신하고 mathes를 result에 더해준다.
  3. 만약 새로 갱신된 team의 수가 1이라면 while문을 종료하고 result를 리턴한다.

/**
 * @param {number} n
 * @return {number}
 */
const numberOfMatches = function (n) {
  let matches = 0;
  let teams = n;
  let result = 0;
  while (1) {
    if (teams % 2 === 0) {
      // 팀의 갯수가 짝수일 때
      matches = Math.floor(teams / 2);
      teams = teams / 2;
      result += matches;
    } else {
      // 팀의 갯수가 홀수일 때
      matches = Math.floor(teams / 2);
      teams = (teams - 1) / 2 + 1;
      result += matches;
    }

    if (teams === 1) break; // 남은 팀의 갯수가 1이면 중단
  }

  return result;
};

3.결과

profile
안녕하세요 :)

0개의 댓글