Distance Between Bus Stops
给一个数组, 里面表示相邻的两个bus stop的距离, 问怎么走最近, 简单的数组遍历.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
class Solution { public int distanceBetweenBusStops(int[] distance, int start, int destination) { int forward = 0; int i = start; while(i != destination){ forward += distance[i++]; if(i == distance.length) i=0; } System.out.println(forward); int backward = 0; int j = start; while(j != destination){ j--; if(j == -1) j = distance.length - 1; backward += distance[j]; } System.out.println(backward); return Math.min(forward, backward); } } |