Algorithm - the minimum time access to all points
Of n points in the plane, the position of the point indicates points [i] = [xi, yi] with integer coordinates. Please calculate a minimum time access to all the points needed (in seconds).
You can move in the plane according to the following rules:
Each second horizontal or vertical direction along a unit length, or across the diagonal (each mobile may be regarded as a unit length in the horizontal and vertical directions within one second).
You must appear in the order of the array to access these points.
Example 1:
Input: points = [[1,1], [3,4], [- 1,0]]
Output: 7
Explanation: an optimum access path is: [1,1] -> [2,2] - > [3,3] -> [3,4] -> [2,3] -> [1,2] -> [0,1] -> [1,0]
from [1,1] to [ 3,4] 3 seconds
from [3,4] to [1,0] requires four seconds
requires a total of seven seconds
example 2:
Input: points = [[3,2], [- 2,2]]
Output: 5
prompt:
- points.length == n
- 1 <= n <= 100
- points[i].length == 2
- -1000 <= points[i][0], points[i][1] <= 1000
Source: stay button (LeetCode)
class Solution {
public int minTimeToVisitAllPoints(int[][] points) {
int sum = 0;
for (int i = 0; i < points.length-1; i++) {
sum += Math.max(Math.abs(points[i][0] - points[i + 1][0]), Math.abs(points[i][1] - points[i + 1][1]));
}
return sum;
}
}
Ideas
After comparison, the x is actually a comparison between the two points from a large distance y is large, whichever is greater distance between two points that count.
notes
- Absolute value method:
int number = -2;
int absNumber = Math.abs(number);
- Take the maximum of two numbers:
int a = 3;
int b = 4;
Math.max(a,b); //输出4
- onTwo-dimensional arrayusage:
Two-dimensional array can be understood as: an array each element of an array.
- example 1:
int[][] arr = new int[a][b];
a two-dimensional array that represents the number of arrays;
B represents the number of elements of each one-dimensional array.
int[][] arr = new int[2][3];
This two-dimensional array has a two dimensional array, it is expressed as: arr [0], arr [ 1];
for each one-dimensional array with 3 elements, each element was written to call: arr [a] [b] , a represents the first of several array, b represents a bit.
- example 2:
int[][] arr = new int[a][];
a two-dimensional array represents the number of arrays, but the number of elements is not given a one-dimensional array, the number of which can be given dynamically.
int[][] arr = new int[2][];
arr[0] = new int[3];
arr[1] = new int[1];
- example 3:
int[][] arr = {{1,2},{3,4,5,6},{7,8,9}};
Directly to the two-dimensional array are given in the declaration.