LC.P2731[移动机器人]

方法一:脑筋急转弯+排序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
private static final int MOD = (int) 1e9 + 7;

public int sumDistance(int[] nums, String s, int d) {
int n = nums.length;
long[] arr = new long[n];
for (int i = 0; i < n; ++i) {
arr[i] = (long) nums[i] + (s.charAt(i) == 'L' ? -d : d);
}
Arrays.sort(arr);
long ans = 0, sum = 0;
for (int i = 0; i < n; ++i) {
ans = (ans + i * arr[i] - sum) % MOD;
sum += arr[i];
}
return (int) ans;
}
}
  • 时间复杂度:$O(nlogn)$
  • 空间复杂度:$O(n)$