当前位置:网站首页>Illustration leetcode - 1184. Distance between bus stops (difficulty: simple)
Illustration leetcode - 1184. Distance between bus stops (difficulty: simple)
2022-07-25 08:49:00 【Javanese Muse】
One 、 subject
There are... On the circular bus route n Individual station , From 0 To n - 1 Number . We know the distance between each pair of adjacent bus stops ,distance[i] Indicates that the number is i The station and number are (i + 1) % n The distance between the stations .
All buses on the loop line can press Clockwise and Anti-clockwise Driving in the same direction .
Return passengers from the starting point start Destination destination The shortest distance between .
Two 、 Example
2.1> Example 1

【 Input 】distance = [1,2,3,4], start = 0, destination = 1
【 Output 】1
【 explain 】 Bus stop 0 and 1 The distance between them is 1 or 9, The minimum is 1.
2.2> Example 2

【 Input 】distance = [1,2,3,4], start = 0, destination = 2
【 Output 】3
【 explain 】 Bus stop 0 and 2 The distance between them is 3 or 7, The minimum is 3.
2.3> Example 3

【 Input 】distance = [1,2,3,4], start = 0, destination = 3
【 Output 】4
【 explain 】 Bus stop 0 and 3 The distance between them is 6 or 4, The minimum is 4.
Tips :
- 1 <= n <= 10^4
- distance.length == n
- 0 <= start, destination < n
- 0 <= distance[i] <= 10^4
3、 ... and 、 Their thinking
3.1> Ideas 1: Forward and reverse double pointers
Since all the buses on the loop line are ok Drive clockwise and counterclockwise . Then we pass two pointers respectively , Start from the beginning and start from the end , Drive , Although the calculation route from the end point to the starting point is also positive , But according to the meaning of the question, it is actually from the beginning to the end , And experience the same distance , therefore , We call counting from the end to the start “ reverse ”. that , At first , Forward count :forwardCount=0, Reverse counting :reverseCount=0, Whether the forward driving is over :forwardDriveFinished=false, Whether the reverse driving is over :reverseDriveFinished=false. As shown in the figure below :

Then when the first run is over , We found that , The reverse form is over ( namely : from index(3) To index(0)), Reverse counting :reverseCount=2. And the positive form is still in progress , Where the positive count :forwardCount=1. because reverseCount > forwardCount, So drive forward and continue .

Then the reverse form has ended in the last cycle , So this wheel can only be driven in a positive direction , Drive to index(2) The nodes of , Forward count :forwardCount=3, because reverseCount < forwardCount, therefore , We can conclude that , The reverse form is shorter ( Although the forward drive continues ...), Now that the result has been determined , Then we can end the forward drive at this time . return reverseCount Value as the result .

3.2> Ideas 2: Compare the results after complete traversal
The advantage of idea one is , When there is a small number of steps in the forward or reverse direction , We don't have to wait for the party with a longer number of steps to complete , As long as the end is completed, the shortest distance can be confirmed , You can end the traversal . But there is more code to implement . and If we want a simple code implementation , We can actually go through a complete loop , Then pass the final result , To judge .
Why can it be determined by a complete traversal ? Suppose the total array is [1, 2, 3, 4, 5, 6, 7, 8], If we start=2,destination=7, that stay [2, 7) Count in the range of , It's the distance in the forward direction . And because the whole journey is a ring road , namely : It's a circle , therefore Out of scope , Is the range of reverse driving . And if the destination=2,start=7 What shall I do? ? Actually sum start=2,destination=7 The calculation is the same , For convenience , We just need to put destination=2,start=7 Transformation for start=2,destination=7, You can count . This way, , The implementation code will be more convenient and tidy . As shown in the figure below :

Four 、 Code implementation
4.1> Realization 1: Forward and reverse double pointers
public int distanceBetweenBusStops1(int[] distance, int start, int destination) {
int forwardCount = 0, reverseCount = 0, startNum = start, destinationNum = destination;
boolean forwardDriveFinished = false, reverseDriveFinished = false;
while (!forwardDriveFinished || !reverseDriveFinished) {
// Take a step forward
if (!forwardDriveFinished) {
forwardCount += distance[startNum];
startNum = (startNum + 1) % distance.length;
if (startNum == destination) {
forwardDriveFinished = true;
}
} else if (forwardCount <= reverseCount) {
return forwardCount;
}
// Take a step backwards
if (!reverseDriveFinished) {
reverseCount += distance[destinationNum];
destinationNum = (destinationNum + 1) % distance.length;
if (start == destinationNum) {
reverseDriveFinished = true;
}
} else if (reverseCount <= forwardCount) {
return reverseCount;
}
}
return Math.min(forwardCount, reverseCount);
}
4.2> Realization 2: Compare the results after complete traversal
public int distanceBetweenBusStops2(int[] distance, int start, int destination) {
int forwardCount = 0, reverseCount = 0;
if (start > destination) {
int temp = destination;
destination = start;
start = temp;
}
for (int i = 0; i < distance.length; i++) {
if (i >= start && i < destination) {
forwardCount += distance[i];
} else {
reverseCount += distance[i];
}
}
return Math.min(forwardCount, reverseCount);
}
That's all for today's article :
Writing is not easy to , An article completed by the author in hours or even days , I only want to exchange you for a few seconds give the thumbs-up & Share .
More technical dry goods , Welcome everyone to follow the official account @ Java Muse 「 Dry cargo sharing , Update daily 」
Previous recommendation
The illustration LeetCode——731. My schedule II( difficulty : secondary )
https://mp.csdn.net/mp_blog/creation/editor/125884328 The illustration LeetCode——3. Longest substring without repeating characters ( difficulty : secondary )
https://mp.csdn.net/mp_blog/creation/editor/125857066LeetCode Work: ——21. Merge two ordered lists ( difficulty : Simple )
https://mp.csdn.net/mp_blog/creation/editor/125840103LeetCode Work: ——565. Array nesting ( difficulty : secondary )
https://mp.csdn.net/mp_blog/creation/editor/125831251
Title source : Power button (LeetCode)
边栏推荐
- Graduation design of wechat small program ordering system of small program completion works (5) assignment
- Review the second time, 220614, video, day03_ Data warehouse design,
- Qt|qlabole change line spacing when displaying multiple lines
- JD cloud and Forrester consulting released a hybrid cloud report that cloud Nativity has become a new engine driving industrial development
- Foundation 31: Selenium positioning dynamic ID element
- IDEA下依赖冲突解决方法
- LeetCode·83双周赛·6129.全0子数组的数目·数学
- PHP reports an error: classes\phpexcel\cell php Line(594) Invalid cell coordinate ESIGN1
- Talk about your transformation test development process
- 哈希表刷题(上)
猜你喜欢

51 MCU peripherals: Motor

公寓报修系统(IDEA,SSM,MySQL)

Leetcode · 83 biweekly race · 6129. Number of all 0 subarrays · mathematics

This is the worst controller layer code I've ever seen

@Autowired注解的实现原理

51 MCU internal peripherals: timer and counter

51单片机内部外设:定时器和计数器

uni-app
![[Sesame Street family] & Bert Bart Roberta](/img/ff/c685065cd413bd4cffd996fd9afeaa.png)
[Sesame Street family] & Bert Bart Roberta

Wechat reservation applet graduation project (7) mid term inspection report of applet completion works
随机推荐
Wechat reservation applet graduation design of applet completion works (1) development outline
Phpexcel reports an error: err_ INVALID_ RESPONSE
Solving a random number problem
Django4.0 + web + MySQL 5.7 realize simple login operation
Wechat reservation applet graduation design of applet completion works (2) applet function
How to do the game plug-in?
Deduct one question every day - 2114. The maximum number of words in the sentence
@Use of data annotation (instead of get and set methods in entity classes)
附加:下半部分sql语句 区/县(数据表)
Recursive call to print every bit of an integer
51单片机内部外设:定时器和计数器
富文本样式文字图片处理
QA robot sequencing model
Tips for improving code sustainability, take connectto method as an example.
Wechat reservation of completed works of applet graduation project (4) opening report
FreeMaker模板引擎
Qt|QLable多行展示时更改行间距
Redis学习笔记
Why use MQ message oriented middleware? These questions must be taken down!
@Autowired注解的实现原理