1. 문제(원본)
On a plane there are n points with integer coordinates points[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 seconds
Example 2:
Input: points = [[3,2],[-2,2]] Output: 5
Constraints:
- points.length == n
- 1 <= n <= 100
- points[i].length == 2
- -1000 <= points[i][0], points[i][1] <= 1000
2. 문제
임의의 점들을 차례로 찾아내어 첫 지점에서 끝 지점에 도착했을 시 얼마나 걸리는 지 구하기
3. 나의 답
class Solution {
func minTimeToVisitAllPoints(_ points: [[Int]]) -> Int {
var count = 0
var start: [Int]? = nil
for element in points {
if start == nil {
start = element
} else {
let maxValue = max((start![0] - element[0]).magnitude,
(start![1] - element[1]).magnitude)
start = element
count += Int(maxValue)
}
}
return count
}
}
4. 다른 유저의 답
#1
class Solution {
func minTimeToVisitAllPoints(_ points: [[Int]]) -> Int {
var seconds = 0
for i in 0..<points.count - 1 {
let x = points[i+1][0]-points[i][0]
let y = points[i+1][1]-points[i][1]
seconds += max(abs(x), abs(y))
}
return seconds
}
}
5. 마무리
처음에는 문제가 잘 이해가 되지 않아 어떻게 풀어야 할지 고민했지만 그냥 해당 거리의 값들을 구하면 되는 것임을 알아냈다.
다른 유저들도 답을 비슷한 방법으로 풀었지만 더욱 간략해서 푼 유저들도 있었다.
코드를 최대한 줄이면서 풀 수 있게 노력해야겠다.
'알고리즘 > 해결' 카테고리의 다른 글
LeetCode617. Merge Two Binary Trees (0) | 2020.03.18 |
---|---|
LeetCode657. Robot Return to Origin (0) | 2020.03.18 |
LeetCode1290. Convert Binary Number in a Linked List to Integer (0) | 2020.03.15 |
LeetCode1323. Maximum 69 Number (0) | 2020.03.08 |
LeetCode1365. How Many Numbers Are Smaller Than the Current Number (0) | 2020.03.08 |