2731. Movement of Robots

Simulation(TLE)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class Solution {
private static final int MOD = 1000000007;

public int sumDistance(int[] nums, String s, int d) {
int[] directions = new int[nums.length];
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == 'L') {
directions[i] = -1;
} else {
directions[i] = 1;
}
}

for (int i = 0; i < d; i++) {
Map<Integer, Set<Integer>> positionToRobotsMap = new HashMap<>(); // 注意每次新建 map, 不能全局使用一个 map, 因为每次全部机器人移动完才知道是否碰撞,不能使用之前的移动结果去进行比较

for (int j = 0; j < nums.length; j++) {
nums[j] += directions[j];

Set<Integer> robots = positionToRobotsMap.computeIfAbsent(nums[j], key -> new HashSet<>());
robots.add(j);
if (robots.size() == 2) {
for (int robot : robots) {
directions[robot] *= -1;
}
} else if (robots.size() > 2) {
directions[j] *= -1;
}
}
}

int sumDistance = 0;
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
sumDistance += (int) (Math.abs((long) nums[i] - nums[j]) % MOD);
sumDistance %= MOD;
}
}

return sumDistance;
}
}

Math + Prefix Sum

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
private static final int MOD = 1000000007;

public int sumDistance(int[] nums, String s, int d) {
for (int i = 0; i < nums.length; i++) {
nums[i] += d * (s.charAt(i) == 'L' ? -1 : 1);
}

Arrays.sort(nums);

long distanceSum = 0;
long prefixDistanceSum = 0;
for (int i = 1; i < nums.length; i++) {
prefixDistanceSum += (long) i * ((long) nums[i] - nums[i - 1]) % MOD; // 注意数字相减前的转型,以防止两个 int 整数相减越界
distanceSum += prefixDistanceSum;
distanceSum %= MOD;
}

return (int) distanceSum;
}
}

References

2731. Movement of Robots