# LeetCode342. Power of 4 / game 243

Posted by Cyberspace on Mon, 07 Feb 2022 22:32:31 +0100

# 342. Power of 4

#### Title Description

```Given an integer, write a function to determine whether it is a power of 4. If yes, return true ；Otherwise, return false .

integer n Is the power of 4, which must be satisfied: there is an integer x bring n == 4x

Example 1:

Input: n = 16
Output: true
Example 2:

Input: n = 5
Output: false
Example 3:

Input: n = 1
Output: true
```

Source: LeetCode

#### thinking

I also want to use the simple one line method, but I don't think much of it. Ha ha, I can only find the position of binary 1

```class Solution {
public boolean isPowerOfFour(int n) {
//The power of 4 is the statistical position of 1. If it is even, it is the power of 4
if(n <= 0)
return false;
int count = 1;
while((n & 1) != 1){
n >>= 1;
count++;
}
count++;
return n == 1 && count % 2 == 0;
}
}
```

The official solution is written by constructing an integer with odd digits of 1, and then sum it with n. if it is 0, it means that it is a power of 4 (on the premise that it is a power of 2)
Or take the remainder of 3. The power of 4 is 1 to 3. If it is 2, the power of 2 is 2 to 3

```class Solution {
public boolean isPowerOfFour(int n) {
return n > 0 && (n & (n - 1)) == 0 && (n & 0xaaaaaaaa) == 0;
//return n > 0 && (n & (n - 1)) == 0 && n % 3 == 1;
}
}
```

# Game 243

How to say this game? It's also the first two seconds. The third one can be done, but it's stuck. The fourth one doesn't look very good. It's basically the same rhythm as the biweekly match on Saturday night. The next goal is still three questions, but the ranking has improved. Ha ha

# 1880. Check whether a word is equal to the sum of two words

#### Title Description

```The letter value of a letter depends on the position of the letter in the alphabet, counting from 0. That is,'a' -> 0,'b' -> 1,'c' -> 2，and so on.

For a string of lowercase letters s For example, its value is equal to s The letter values of each letter in are connected in sequence and converted into corresponding integers.

For example, s = "acb" ，Connect the letter values of each letter in turn to get "021" ，Convert to integer to get 21.
Here are three strings firstWord,secondWord and targetWord ，Each string is represented by 'a' reach 'j' (contain 'a' and 'j' )Composed of lowercase English letters.

If firstWord and secondWord The sum of the values is equal to targetWord Numeric value of, return true ；Otherwise, return false .

Example 1:

Input: firstWord = "acb", secondWord = "cba", targetWord = "cdb"
Output: true
Explanation:
firstWord The value of is "acb" -> "021" -> 21
secondWord The value of is "cba" -> "210" -> 210
targetWord The value of is "cdb" -> "231" -> 231
Due to 21 + 210 == 231 ，return true
Example 2:

Input: firstWord = "aaa", secondWord = "a", targetWord = "aab"
Output: false
Explanation:
firstWord The value of is "aaa" -> "000" -> 0
secondWord The value of is "a" -> "0" -> 0
targetWord The value of is "aab" -> "001" -> 1
Due to 0 + 0 != 1 ，return false
Example 3:

Input: firstWord = "aaa", secondWord = "a", targetWord = "aaaa"
Output: true
Explanation:
firstWord The value of is "aaa" -> "000" -> 0
secondWord The value of is "a" -> "0" -> 0
targetWord The value of is "aaaa" -> "0000" -> 0
Due to 0 + 0 == 0 ，return true
```

Source: LeetCode

#### thinking

There's nothing to say. Just turn it into a number and judge the addition

```class Solution {
public boolean isSumEqual(String firstWord, String secondWord, String targetWord) {
int num1 = 0;
for(int i = 0; i < firstWord.length(); i++){
num1 = num1 * 10 + firstWord.charAt(i) - 'a';
}
int num2 = 0;
for(int i = 0; i < secondWord.length(); i++){
num2 = num2 * 10 + secondWord.charAt(i) - 'a';
}
int num3 = 0;
for(int i = 0; i < targetWord.length(); i++){
num3 = num3 * 10 + targetWord.charAt(i) - 'a';
}
return num1 + num2 == num3;
}
}
```

# Maximum value after insertion 1881

#### Title Description

```Give you a very large integer n And an integer number x ，Large integer n Represented by a string. n Each digit and number in x Are in closed range [1, 9] Medium, and n May represent a negative number.

Are you going to pass n Insert anywhere in the decimal representation of x To maximize n Value of ​​​​​​. But it cannot be inserted to the left of the minus sign x .

For example, if n = 73 And x = 6 ，Then the best solution is to insert 6 between 7 and 3 so that n = 763 .
If n = -55 And x = 2 ，Then the best solution is to insert 2 before the first 5 to make n = -255 .
Returns the value represented by a string after the insert operation n Maximum value of.

Example 1:

Input: n = "99", x = 9
Output:"999"
Explanation: no matter where 9 is inserted, the result is the same.
Example 2:

Input: n = "-13", x = 2
Output:"-123"
Explanation: to n Insert in x Can get -213,-123 perhaps -132 ，The biggest of the three is -123 .
```

Source: LeetCode

#### thinking

I was still thinking about how to deal with 0. As a result, there was no 0. Needless to say

```class Solution {
public String maxValue(String n, int x) {
//If n is a positive number, insert it from left to right. If you find the first number greater than, insert it to the left
//If it is negative, find the first number less than and insert it to the left
int l = n.length();
boolean flag = n.charAt(0) == '-' ? false : true;
int index = 0;
if(flag){
while(index < l){
char c = n.charAt(index);
if(x > c - '0')
break;
index++;
}
}else{
index = 1;
while(index < l){
char c = n.charAt(index);
if(x < c - '0')
break;
index++;
}
}
char[] s = new char[l + 1];
for(int i = 0; i <= l; i++){
if(i < index)
s[i] = n.charAt(i);
else if(i == index)
s[i] = (char)(x + 48);
else
s[i] = n.charAt(i - 1);
}
return new String(s);

}
}
```

# 1882. Use the server to process tasks

#### Title Description

```Give you an array of integers with two subscripts starting from 0 servers and tasks ，The length is n​​​​​​ and m​​​​​​ . servers[i] Is the first i​​​​​​​​​​ Weight of servers, and tasks[j] Is dealing with the second j​​​​​​ The time (in seconds) required for a task.

You are running a simulation system. After all tasks are processed, the system will shut down. Each server can only process one task at a time. The 0th task can start processing in the 0th second. Accordingly, the 0th task j Task on j Seconds to start processing. Processing section j When a task, you need to assign it an idle server with the least weight. If there are multiple idle servers with the same weight, please select the server with the smallest subscript. If an idle server is on the t Seconds allocated to the second j Task, then t + tasks[j] When it is idle, it will be restored.

If there are no idle servers, you must wait until an idle server appears and process the remaining tasks as early as possible. If there are multiple tasks waiting to be assigned, the assignment is completed in the order of increasing subscripts.

If there are multiple idle servers at the same time, multiple tasks can be assigned to them at the same time.

Construction length is m Answer array ans ，among ans[j] Is the first j The subscript of the server to which the task is assigned.

Returns an array of answers ans​​​​ .

Example 1:

Input: servers = [3,3,2], tasks = [1,2,3,2,1,2]
Output:[2,2,0,2,1,2]
Explanation: the chronological order of events is as follows:
- 0 Second, the 0th task is added to the task queue and processed by the second server until 1 second.
- 1 Seconds, the second server is idle, the first task is added to the task queue, and the second server is used to process it for 3 seconds.
- 2 Second, the second task is added to the task queue and processed by the 0th server for 5 seconds.
- 3 Seconds, the second server is idle, the third task is added to the task queue, and the second server is used to process it for 5 seconds.
- 4 Second, the fourth task is added to the task queue and processed by the first server for 5 seconds.
- 5 Seconds, all servers are idle, the fifth task is added to the task queue, and the second server is used to process it for 7 seconds.
Example 2:

Input: servers = [5,1,4,3,2], tasks = [2,1,2,4,5,2,1]
Output:[1,4,1,4,1,3,2]
Explanation: the chronological order of events is as follows:
- 0 Second, the 0th task is added to the task queue and processed by the first server for 2 seconds.
- 1 Second, the first task is added to the task queue and processed by the fourth server for 2 seconds.
- 2 Seconds, the first and fourth servers are idle, the second task is added to the task queue, and the first server is used for processing until 4 seconds.
- 3 Second, the third task is added to the task queue and processed by the fourth server for 7 seconds.
- 4 Seconds, the first server is idle, the fourth task is added to the task queue, and the first server is used for processing until 9 seconds.
- 5 Second, the fifth task is added to the task queue and processed by the third server for 7 seconds.
- 6 Second, the sixth task is added to the task queue and processed by the second server for 7 seconds.
```

Source: LeetCode

#### thinking

Every time I see such a long series of questions, I feel like simulation
Then I want to put the servers in the priority queue and sort them according to the weight and position in the servers array; In addition, a hash table is used to store the key value pairs of < time, server >, indicating the current time and which servers have completed their work
Then traverse the time. If the server has completed the work at the current time, it will be put into the priority queue; If there is work to be completed at present, check whether there is a server in the priority queue. If so, arrange it into the map set.

In this way, the following code is written. The example passed, but the submission timed out. However, the timeout was not when the array was large, but when it was less than ten. That indicates that there is a problem with the code. Here is the code written at that time:

```class Solution {
//Let's simulate it
//The priority queue is put into the server and sorted by weight and subscript
//Then traverse the time. If the server can be allocated, pop up the server, record the return time and store it in a hash table
PriorityQueue<int[]> pq = new PriorityQueue<>(new Comparator<int[]>(){
public int compare(int[] a, int[] b){
return a[0] == b[0] ? a[1] - b[1] : a[0] - b[0];
}
});
int m = servers.length;
for(int i = 0; i < m; i++){
pq.offer(new int[]{servers[i], i});
}
Map<Integer, List<Integer>> map = new HashMap<>();
int[] res = new int[n];
int index = 0;
for(int i = 0; i < n; i++){
//At the current time, whether there is work completed, whether there is work completed, and idle the server
if(map.containsKey(i)){
List<Integer> ser = map.get(i);
map.remove(i);
for(Integer s : ser){
pq.offer(new int[]{servers[s], s});
}
}
while(index <= i){
if(!pq.isEmpty()){
res[index] = pq.peek()[1];
List<Integer> list = map.get(i + tasks[index]);
}else{
}
index++;
}
}
if(index == n)
break;
}
return res;
}
}
```

There should be a problem with the while part. Change it to see if it works. Make a simple change and lose to the timeout, but it's also expected, because I add time one by one. In fact, it can be changed to one task by one in the tasks, because the task processing is from left to right, so it won't be changed here, and the problem solving idea is similar to mine
This is the first time I changed it

```class Solution {
//Let's simulate it
//The priority queue is put into the server and sorted by weight and subscript
//Then traverse the time. If the server can be allocated, pop up the server, record the return time and store it in a hash table
PriorityQueue<int[]> pq = new PriorityQueue<>(new Comparator<int[]>(){
public int compare(int[] a, int[] b){
return a[0] == b[0] ? a[1] - b[1] : a[0] - b[0];
}
});
int m = servers.length;
for(int i = 0; i < m; i++){
pq.offer(new int[]{servers[i], i});
}
Map<Long, List<Integer>> map = new HashMap<>();
int[] res = new int[n];
int index = 0;
//The maximum length of tasks is 200000, and the maximum value of m and n is 200000, so the time is 400000 at most
//No, it should be by
for(long i = 0; i < 40000000001l; i++){
//At the current time, whether there is work completed, whether there is work completed, and idle the server
if(map.containsKey(i)){
List<Integer> ser = map.get(i);
map.remove(i);
for(Integer s : ser){
pq.offer(new int[]{servers[s], s});
}
}
//If the start time of the current task is less than i, it means it can start
while(index <= i){
//If a server is idle
if(!pq.isEmpty()){
//Take out the number of the first server
res[index] = pq.peek()[1];
//If the time point exists in the hash table, insert the server into the list collection
List<Integer> list = map.get(i + tasks[index]);
//If you don't have this number, create this collection
}else{
}
index++;
if(index == n)
break;
//If not, just jump out
}else{
break;
}
}
if(index == n)
break;
}
return res;
}
}
```

Then I looked at the problem solution and found that as long as the time when the server is occupied is directly adjusted to the idle time of the next server, I can AC. then I change the original HashMap to TreeMap, which can sort the server time. Then, every time the server is occupied, the time can jump to map Firstkey(), but this is the first time I have used this method
Then go straight to Shuangbai, ha ha

```class Solution {
//Let's simulate it
//The priority queue is put into the server and sorted by weight and subscript
//Then traverse the time. If the server can be allocated, pop up the server, record the return time and store it in a hash table
PriorityQueue<int[]> pq = new PriorityQueue<>(new Comparator<int[]>(){
public int compare(int[] a, int[] b){
return a[0] == b[0] ? a[1] - b[1] : a[0] - b[0];
}
});
int m = servers.length;
for(int i = 0; i < m; i++){
pq.offer(new int[]{servers[i], i});
}
TreeMap<Long, List<Integer>> map = new TreeMap<>();
int[] res = new int[n];
int index = 0;
//The maximum length of tasks is 200000, and the maximum value of m and n is 200000, so the time is 400000 at most
//No, it should be by
for(long i = 0; i < Long.MAX_VALUE; i++){
//At the current time, whether there is work completed, whether there is work completed, and idle the server
if(map.containsKey(i)){
List<Integer> ser = map.get(i);
map.remove(i);
for(Integer s : ser){
pq.offer(new int[]{servers[s], s});
}
}
//If the start time of the current task is less than i, it means it can start
while(index <= i){
//If a server is idle
if(!pq.isEmpty()){
//Take out the number of the first server
res[index] = pq.peek()[1];
//If the time point exists in the hash table, insert the server into the list collection
List<Integer> list = map.get(i + tasks[index]);
//If you don't have this number, create this collection
}else{
}
index++;
if(index == n)
break;
//If not, just jump out
//i set the next time when the server is not available
}else{
i = map.firstKey() - 1;
break;
}
}
if(index == n)
break;
}
return res;
}
}
```

# 1883. Minimum number of skip breaks to arrive at the meeting site on time

#### Title Description

```Give you an integer hoursBefore ，Indicates the number of available hours left for you to go to the meeting. To successfully arrive at the meeting, you must pass through n This road. The length of the road is expressed as n Array of integers dist Means, where dist[i] Represents the second i The length of the road in kilometers. Give you another integer speed ，Indicates how fast you are moving along the road (in kilometers per hour).

When you pass the second i After this road, you must rest and wait until the next integer hour to continue to pass the next road. Note: you don't need to rest after passing the last road, because you have arrived at the meeting site at that time.

For example, if you go through a road, use 1.4 Hours, then you must stop and wait until 2 hours before you can continue to pass the next road. If it takes exactly 2 hours to pass through a road, there is no need to wait and you can continue directly.
However, in order to arrive on time, you can choose to skip some road breaks, which means you don't have to wait for the next whole hour. Note that this means that you may reach the next path at different times than not skipping any rest time.

For example, suppose 1 is used through the first road.4 Hours, and 0 is used through the second road.6 Hours. The break time to skip Road 1 means that you will finish crossing road 2 in exactly 2 hours and you can start crossing road 3 immediately.
Return the minimum number of skips required to arrive at the meeting site on time. If you can't attend the meeting on time, return -1 .

Example 1:

Input: dist = [1,3,2], speed = 4, hoursBefore = 2
Output: 1
Explanation:
If you don't skip any breaks, you'll use (1/4 + 3/4) + (3/4 + 1/4) + (2/4) = 2.5 Hours to arrive at the meeting site.
You can skip the first rest time and share ((1/4 + 0) + (3/4 + 0)) + (2/4) = 1.5 Arrive at the meeting site within hours.
Note that the second rest time is shortened to 0. Since you skip the first rest time, you complete the passage of the second road in an integer hour.
Example 2:

Input: dist = [7,3,5,5], speed = 2, hoursBefore = 10
Output: 2
Explanation:
If you don't skip any breaks, you'll use (7/2 + 1/2) + (3/2 + 1/2) + (5/2 + 1/2) + (5/2) = 11.5 Hours to arrive at the meeting site.
You can skip the first and third breaks and share ((7/2 + 0) + (3/2 + 0)) + ((5/2 + 0) + (5/2)) = 10 Arrive at the meeting site within hours.
Example 3:

Input: dist = [7,3,5,5], speed = 1, hoursBefore = 10
Output:-1
Explanation: even if you skip all the rest time, you can't attend the meeting on time.
```

Source: LeetCode

#### thinking

At first glance, the background of the second question of last week's competition is a little similar, but this question has more skipping... And if one point is skipped, the next point should also be taken into account
Dynamic programming again
dp[i][j] indicates that the i-th section of the road has been completed and the shortest time of j skips has been used
See this writing is very good, learn it
The processing of floating point precision needs attention!!!!!

```class Solution {
public int minSkips(int[] dist, int speed, int hoursBefore) {
int n= dist.length;
//dp[i][j] indicates the shortest time taken to complete section I of the road and skip times j
long[][] dp = new long[n + 1][n + 1];
for(int i = 1; i <= n; i++){
for(int j = 0; j <= n; j++){
dp[i][j] = Integer.MAX_VALUE;
}
}

//state transition
//Special treatment for the last section of road
for(int i = 1; i <= n - 1; i++){
for(int j = 0; j <= i; j++){
//Due to the precision limitation of floating-point numbers, direct division will lead to the loss of precision, so save the molecules first, and finally do the division uniformly
//If j is 0, it means no skipping, which is the same as the second question of last week's competition
//But here dp is the distance
if(j == 0){
dp[i][j]=(dp[i-1][j]+dist[i-1]+speed-1)/speed*speed;
//If there is skipping, the current distance can be skipped or not
}else{
//First, skip; Second, don't skip
dp[i][j]=Math.min(dp[i-1][j-1]+dist[i-1],(dp[i-1][j]+dist[i-1]+speed-1)/speed*speed);
}
}
}
//Process the last distance, and the last distance does not need to be skipped
for(int i=0;i<=n;i++){
if((double)(dp[n-1][i]+dist[n-1])/(double)speed<=(double)hoursBefore)
return i;
}
return -1;
}
}

Author: garett