Leetcode 1688. Count of Matches in Tournament
You are given an integer n
, the number of teams in a tournament. A match is held between two teams, and the winner of each match proceeds to the next round. The process continues until there is only one team remaining. You need to determine and return the total number of matches played in the tournament until a winner is decided.
n
be zero or negative?
1
, which means n >= 1
.The strategy to solve this is straightforward:
For every round:
n
is even, the number of matches is n/2
and n
for the next round becomes n/2
.n
is odd, the number of matches is (n-1)/2
and n
for the next round becomes (n-1)/2 + 1
due to one team getting a bye.Here is how you can implement this in C++:
class Solution {
public:
int numberOfMatches(int n) {
int totalMatches = 0;
while (n > 1) {
if (n % 2 == 0) {
totalMatches += n / 2;
n /= 2;
} else {
totalMatches += (n - 1) / 2;
n = (n - 1) / 2 + 1;
}
}
return totalMatches;
}
};
totalMatches
to 0.n > 1
).n
is even, add n / 2
to totalMatches
and update n
to n / 2
.n
is odd, add (n - 1) / 2
to totalMatches
and update n
to (n - 1) / 2 + 1
.totalMatches
after exiting the loop.The time complexity of this approach is O(log n)
because in each round, the number of teams is approximately halved. Thus, the number of iterations of the loop is logarithmic with respect to n
.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?