【leetcode】1266. Minimum Time Visiting All Points
2024-09-05 15:08:42
题目如下:
On a plane there are
n
points with integer coordinatespoints[i] = [xi, yi]
. Your task is to find the minimum time in seconds to visit all points.You can move according to the next rules:
- In one second always you can either move vertically, horizontally by one unit or diagonally (it means to move one unit vertically and one unit horizontally in one second).
- You have to visit the points in the same order as they appear in the array.
Example 1:
Input: points = [[1,1],[3,4],[-1,0]]
Output: 7
Explanation: One optimal path is [1,1] -> [2,2] -> [3,3] -> [3,4] -> [2,3] -> [1,2] -> [0,1] -> [-1,0]
Time from [1,1] to [3,4] = 3 seconds
Time from [3,4] to [-1,0] = 4 seconds
Total time = 7 secondsExample 2:
Input: points = [[3,2],[-2,2]]
Output: 5Constraints:
points.length == n
1 <= n <= 100
points[i].length == 2
-1000 <= points[i][0], points[i][1] <= 1000
解题思路:优先走斜线,直到满足起点的x坐标等于终点的x坐标或者起点的y坐标等于终点的y坐标;然后走直线,直至到达终点。
代码如下:
class Solution(object):
def minTimeToVisitAllPoints(self, points):
"""
:type points: List[List[int]]
:rtype: int
"""
def calc(x1,y1,x2,y2):
distance = min(abs(x1-x2),abs(y1-y2))
return distance + abs(abs(x1-x2) - distance) + abs(abs(y1-y2) - distance)
res = 0
for i in range(len(points)-1):
res += calc(points[i][0],points[i][1],points[i+1][0],points[i+1][1])
return res
最新文章
- Java javassist动态代理
- MapReduce编程示例
- android学习笔记30——AndroidMainfest.xml
- 【转】【Android测试技巧】01. root后adb shell默认不是root用户时,如何将文件放入手机系统中
- 从零开始搭建TestCpp工程
- git pull 部署问题一揽子问题解决
- shell script 入门 笔记
- erlang四大behaviour之三-gen_event
- .net 企业管理系统快熟搭建框架
- Spring事务管理—aop:pointcut expression解析
- React 虚拟 DOM 的差异检测机制
- WebGL绘制有宽度的线
- Python day 05
- (转)db2top详解
- selective search
- 转:vue+canvas如何实现b站萌系登录界面
- C# System.Collections.Stack
- Java基础加强总结(一)——注解(Annotation)
- Spring Boot 揭秘与实战(二) 数据存储篇 - JPA整合
- HttpServlet Service方法