LeetCode 2211. Count Collisions on a Road|世界播报

时间:2023-03-25 12:50:11 来源: 哔哩哔哩

There are ncars on an infinitely long road. The cars are numbered from 0to n - 1from left to right and each car is present at a unique point.

You are given a 0-indexed string directionsof length ndirections[i]can be either 'L''R', or 'S'denoting whether the ithcar is moving towards the left, towards the right, or staying at its current point respectively. Each moving car has the same speed.

The number of collisions can be calculated as follows:


(资料图片仅供参考)

When two cars moving in opposite directions collide with each other, the number of collisions increases by 2.

When a moving car collides with a stationary car, the number of collisions increases by 1.

After a collision, the cars involved can no longer move and will stay at the point where they collided. Other than that, cars cannot change their state or direction of motion.

Return the total number of collisions that will happen on the road.

Example 1:

Input: directions = "RLRSLL"

Output: 5

Explanation:The collisions that will happen on the road are: 

- Cars 0 and 1 will collide with each other. Since they are moving in opposite directions, the number of collisions becomes 0 + 2 = 2.

- Cars 2 and 3 will collide with each other. Since car 3 is stationary, the number of collisions becomes 2 + 1 = 3. 

- Cars 3 and 4 will collide with each other. Since car 3 is stationary, the number of collisions becomes 3 + 1 = 4. 

- Cars 4 and 5 will collide with each other. 

After car 4 collides with car 3, it will stay at the point of collision and get hit by car 5. The number of collisions becomes 4 + 1 = 5.

Thus, the total number of collisions that will happen on the road is 5.

Example 2:

Input: directions = "LLRR"

Output: 0

Explanation:No cars will collide with each other. Thus, the total number of collisions that will happen on the road is 0.

Constraints:

1 <= directions.length <= 105

directions[i]is either 'L''R', or 'S'.

这个是过了代码,先说说不过的代码,将RL的变成SS,然后就是去判断每个位置最近的S在哪里,L的判断左边的S,R的判断右边的S,然后就Time Limit Exceed了。

仔细想想,直接先将RL的变成SS,然后找到最左端的S的位置,跟最右端S的位置,只要是L的位置小于最左端S的位置,R的位置小于最右端S的位置,那么一定会碰撞的。然后就过了。

Runtime: 41 ms, faster than 50.00% of Java online submissions for Count Collisions on a Road.

Memory Usage: 44.2 MB, less than 15.85% of Java online submissions for Count Collisions on a Road.

标签:

相关文章

社会面清零后第十天,三问吉林省复工复产怎样了

新华社长春4月23日电 题:社会面清零后第十天,三问吉林省复工复产怎样了 新华社记者段续、张建、赵丹丹...

来源:2022-04-24

青海海北州门源县发生3.9级地震 震源深度10千米

4月23日电 据国家地震台网官方微博消息,中国地震台网正式测定:04月23日22时07分在青海海北州门源县(...

来源:2022-04-24

山西太原万柏林区报告1例无症状感染者 公布行程轨迹

(抗击新冠肺炎)山西太原万柏林区报告1例无症状感染者 公布行程轨迹 太原4月23日电 (记者 李新锁)山西...

来源:2022-04-24

上海战疫:从严从重从快查处食品安全违法行为

(抗击新冠肺炎)上海战疫:从严从重从快查处食品安全违法行为 上海4月23日电 (记者 许婧)近日,上海出现...

来源:2022-04-24

杭州本轮疫情已发现98例阳性感染者 有进一步扩散可能

杭州4月23日电(张煜欢 崔倩娴)23日,记者从杭州市新冠肺炎疫情防控工作新闻发布会上获悉,截至23日18时...

来源:2022-04-24

精彩推送

X 关闭

X 关闭