Open songyy5517 opened 3 months ago
Approach: Queue
Complexity Analysis
class Solution {
public String predictPartyVictory(String senate) {
// Intuition: Queue & Greedy
// 1. Exception handling
if (senate == null || senate.length() == 0)
return "";
// 2. Define two queues to store the index of radient and dire
Queue<Integer> radiant = new LinkedList();
Queue<Integer> dire = new LinkedList();
// 3. Add the index of each senator to their queues
for (int i = 0; i < senate.length(); i++){
if (senate.charAt(i) == 'R')
radiant.add(i);
else
dire.add(i);
}
// 3. Simulate the voting process
while (!radiant.isEmpty() && !dire.isEmpty()){
int r = radiant.remove(), d = dire.remove();
if (r > d)
dire.add(d + senate.length());
else
radiant.add(r + senate.length());
}
return dire.isEmpty() ? "Radiant" : "Dire";
}
}
2024/5/25
In the world of Dota2, there are two parties: the Radiant and the Dire. The Dota2 senate consists of senators coming from two parties. Now the Senate wants to decide on a change in the Dota2 game. The voting for this change is a round-based procedure. In each round, each senator can exercise one of the two rights:
Given a string senate representing each senator's party belonging. The character 'R' and 'D' represent the Radiant party and the Dire party. Then if there are n senators, the size of the given string will be n.
The round-based procedure starts from the first senator to the last senator in the given order. This procedure will last until the end of voting. All the senators who have lost their rights will be skipped during the procedure.
Suppose every senator is smart enough and will play the best strategy for his own party. Predict which party will finally announce the victory and change the Dota2 game. The output should be "Radiant" or "Dire".
Example 1:
Example 2:
Intuition The problem is basically to find the part that finally exists after the voting process. From the description, we know that a unbanned senator can ban a subsequent senator of the other party. Therefore, we can define two queues to store all the indices of senators of each party respectively. Then simulate the voting process with these two queues. Specifically, when the two queues are not empty, we compare the top element of each queue, the smaller index would vote first. In this way, we remove the top element of the other queue, and add the smaller index plus the size of the whole senators in the same queue. Repeat the above steps until there is one empty queue. Therefore, the winner is the non-empty party.