Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Leetcode 2731. Movement of Robots #265

Open
Woodyiiiiiii opened this issue Jun 12, 2023 · 0 comments
Open

Leetcode 2731. Movement of Robots #265

Woodyiiiiiii opened this issue Jun 12, 2023 · 0 comments

Comments

@Woodyiiiiiii
Copy link
Owner

Woodyiiiiiii commented Jun 12, 2023

2731. Movement of Robots

2731. Movement of Robots

类似问题:
735. Asteroid Collision
2751. Robot Collisions

这道题是双周赛第三题。很好的思维题

问题难点主要是如何解决碰撞问题及碰撞后的位置问题。既然知道了答案,这里我就尝试正推一下,看看思路如何想到真正的解法。

不妨从时间复杂度出发,最多排序下。接着只能在O(n)条件下完成了,而且d这么大,所以也不能一个个研究了。然后题目求的是两两之间的距离,所以我们最好知道所有robots最后的位置。但碰撞有很多种情况,如何计算robots的位置呢?从最简单的情况考虑,考虑robots只碰撞一次,碰撞后两球往相反的位置移动,我们可以假设robots并没改变方向,仍按照之前的方向移动,因为我们只关注robots的位置,不需要对应,这样就能解决robots的位置了。

既然知道了每个robot的位置,接下来就是求两两之间的距离了。只能在O(n)下完成,假设一次遍历到位置j,其与之前的robots位置计算是nums[j] - nums[j-1] + nums[j] - nums[j-2]...,可以简化成j个nums[j]相乘再减去之前的位置前缀和。

class Solution {
    public int sumDistance(int[] nums, String s, int d) {
        int n = nums.length;
        List<Integer> positions = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            int position = s.charAt(i) == 'L' ? nums[i] - d : nums[i] + d;
            positions.add(position);
        }
        Collections.sort(positions);
        final int MOD = (int) (1e9 + 7);
        long ans = 0, preSum = positions.get(0);
        for (int i = 1; i < positions.size(); i++) {
            ans = (ans + (long) positions.get(i) * i - preSum + MOD) % MOD;
            preSum += positions.get(i);
        }
        return (int)ans;
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant