--------------下面是今天的算法题--------------
来看下今天的算法题,这题是LeetCode的第1266题:访问所有点的最小时间,难度是简单。
输入:points = [[1,1],[3,4],[-1,0]]
输出:7
解释:一条最佳的访问路径是: [1,1] -> [2,2] -> [3,3] -> [3,4] -> [2,3] -> [1,2] -> [0,1] -> [-1,0]
从 [1,1] 到 [3,4] 需要 3 秒
从 [3,4] 到 [-1,0] 需要 4 秒
一共需要 7 秒
points.length == n
1 <= n <= 100
points[i].length == 2
-1000 <= points[i][0], points[i][1] <= 1000
问题分析
public int minTimeToVisitAllPoints(int[][] points) {
int ans = 0;
for (int i = 1; i < points.length; i++)
ans += Math.max(Math.abs(points[i][0] - points[i - 1][0]),
Math.abs(points[i][1] - points[i - 1][1]));
return ans;
}
public:
int minTimeToVisitAllPoints(vector<vector<int>> &points) {
int ans = 0;
for (int i = 1; i < points.size(); i++)
ans += max(abs(points[i][0] - points[i - 1][0]),
abs(points[i][1] - points[i - 1][1]));
return ans;
}