Generally refers to the ring problem has two solutions, the ultimate answer is to return two of the best. Common are:
- Angle clock
- The distance between the bus station
The general problem-solving ideas are similar, from these points not wrong:
- First, find the total length of the sum.
- After the solution was then determined visually sub.
- Finally, by comparing
sum - sub
thesub
selected answer merits.
...
int sum = ?
int sub = ?
return chioce(sub-sub, sub);
...
Clock angle C_01
Method a: Method of complementary
Complexity Analysis
- time complexity: ,
- Space complexity: ,
The distance between the bus station C_02
With n stations on the ring bus routes, in sequence from 0 to n - 1 is numbered. We know the distance between each pair of adjacent bus stop, distance [i] represents the number of stations and the number i is the distance between the (i + 1)% n stations.
Bus on the ring can travel in the direction of clockwise and counterclockwise.
Passengers return to the starting point to start from the shortest distance between destination destination.
输入:distance = [1,2,3,4], start = 0, destination = 3
输出:4
解释:公交站 0 和 3 之间的距离是 6 或 4,最小值是 4。
Method a: Method of complementary
And the angle clock seeking nature to a class of questions. Because it is a circular area inside the shortest path, so we should be a little "opportunistic" look,
- We first find the total length of the sum, and obtaining the distance d s to dis.
- Finally, compare the sum-dis dis size can be.
public int distanceBetweenBusStops(int[] distance, int start, int destination) {
int s = Math.min(start, destination);
int d = Math.max(start, destination);
int sum = 0;
for (int dis : distance)
sum += dis;
int dis = 0;
for (int i = s; i < d; i++)
dis += distance[i];
return Math.min(sum-dis, dis);
}
Complexity Analysis
- time complexity: ,
- Space complexity: ,
A_04
method one:
Complexity Analysis
- time complexity: ,
- Space complexity: ,