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<>();
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; } }
|