- Today
- Total
- ์กธ์ ์ํ
- ์๋ฃ๊ตฌ์กฐ
- MST
- database
- array
- tree
- BFS
- ๋ฒจ๋งํฌ๋
- spring
- pytorch
- ์๋ฐ
- CS
- ๊ทธ๋ฆฌ๋
- ๊ตฌํ
- OOP
- Graph
- ์ธํด
- dp
- ๋ค์ต์คํธ๋ผ
- ์์์ ๋ ฌ
- leetcode
- ํ๋ก๊ทธ๋๋จธ์ค
- ๋ฐฑ์ค
- PS
- ๋ฐฑ์๋
- Algorithm
- ๋ฌธ๋ฒ
- ์๋ฐ์์ ์
- java
- ๋ฐ์ดํฐ๋ฒ ์ด์ค
Partially Committed
[LEETCODE] 1779.Find Nearest Point That Has the Same X or Y Coordinate ๋ณธ๋ฌธ
[LEETCODE] 1779.Find Nearest Point That Has the Same X or Y Coordinate
WonderJay 2022. 10. 11. 15:38
TITLE : 1779.Find Nearest Point That Has the Same X or Y Coordinate
Description : You are given two integers,xandy, which represent your current location on a Cartesian grid:(x, y). You are also given an arraypointswhere eachpoints[i] = [ai, bi]represents that a point exists at(ai, bi). A point isvalidif it shares the same x-coordinate or the same y-coordinate as your location.
Return the index (0-indexed) of the valid point with the smallest Manhattan distance from your current location. If there are multiple, return the valid point with the smallest index. If there are no valid points, return -1.
The Manhattan distance between two points (x1, y1) and (x2, y2) is abs(x1 - x2) + abs(y1 - y2).
์ ๋ ฅ ์ขํ x,y ์ ๋ํด์, points ์ ์ ์ฅ๋ ์ขํ๋ค์ด ์ ํจํ๋ฉด Manhattan distance(l1 - norm) ์ ๊ณ์ฐํ๋๋ฐ, ์ต์ Manhattan distance ๋ฅผ ๊ฐ์ง๋ ์ขํ์ ์ธ๋ฑ์ค(0-indexed)๋ฅผ ๋ฐํํ๋ฉด ๋๋ค. (์ ํจํ ์ขํ๊ฐ ์๋ ๊ฒฝ์ฐ์๋ -1 ์ ๋ฐํ.)
์ด๋ฅผ ํ๊ธฐ ์ํด์ ์ฒ์์๋ pair<int, int> // { distance, index } ๋ฅผ element ๋ก ๊ฐ์ง๋ 1-d vector ์ ์ ์ธํด์, ์ ํจํ ์ขํ๋ผ๋ฉด distance ์ index ๋ฅผ push_back ํด์ฃผ๊ณ , ๊ทธ vector ์ distance ๊ธฐ์ค์ผ๋ก ์ ๋ ฌํ ๋ค์ v[0].second ๋ฅผ ๋ฐํํ๋ฉด ๋ ๊ฒ์ด๋ผ๊ณ ์๊ฐํด์ ๊ตฌํํ๋ ค๊ณ ํ์ผ๋, ๊ตณ์ด vector ์ ๋ถํ์ํ๊ฒ ๋ ์ ์ธํด์ฃผ์ง ์์๋ ๊ฐ๋ฅํ๋ค๋ ๊ฒ์ ๋๊ผ๋ค. points ๋ฐฐ์ด์ ์ํํ๋ฉฐ ๊ฐ ์ขํ์ ์ ํจ์ฑ์ ๊ฒ์ฌํ ๋ค, ์ ํจํ ์ขํ์ ๋ํด์ distance ๊ฐ์ ๊ณ์ฐํ๊ณ maxi ์ ๋น๊ตํด์ ๋ ์๋ค๋ฉด maxi ๋ฅผ distance ๊ฐ์ผ๋ก ์นํํ๊ณ ans ์ ์ธ๋ฑ์ค๊ฐ์ ์ ์ฅํ์ฌ ํ์ดํ ์ ์๋ค.
( ๋ค์ ๋ณด๋๊น maxi ๋ ์ต์ ๊ฑฐ๋ฆฌ๋ฅผ ์ ์ฅํ๋ ์ญํ ์ธ๋ฐ maxi ๋ผ๋ ์ด๋ฆ์ผ๋ก ์ง์ด์ค ๊ฑฐ๋ ์๋ชป๋ ๊ฒ ๊ฐ๋ค. ์ํ๊ธฐ๊ฐ์ด๋ผ ์ ์ ์ด ์๋๋ณด๋ค... mini ์ ๊ฐ์ด ์ด๋ฆ์ ์ง์ด์ฃผ๋ ๊ฒ ์ณ๊ฒ ๋ค. )
[C++]
class Solution {
public:
int nearestValidPoint(int x, int y, vector<vector<int>>& points) {
int dist = 0; int ans = -1; int maxi = INT_MAX;
for (int i = 0; i < points.size(); i++) {
if (x == points[i][0] || y == points[i][1]) {
dist = abs(x - points[i][0]) + abs(y - points[i][1]);
if (dist < maxi) {
maxi = dist;
ans = i;
}
}
}
return ans;
}
};
์๊ฐ๋ณต์ก๋ : O(N)
'๐ฅ Algorithm || ๋ฌธ์ ํ์ด > PS' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[LEETCODE] 1502. Can Make Arithmetic Progression From Sequence (0) | 2022.10.12 |
---|---|
[LEETCODE] 1822. Sign of the Product of an Array (0) | 2022.10.12 |
[LEETCODE] 1281. Subtract the Product and Sum of Digits of an Integer (0) | 2022.10.10 |
[LEETCODE] 191.Number of 1 Bits (0) | 2022.10.10 |
[LEETCODE] 1491. Average Salary Excluding the Minimum and Maximum Salary (0) | 2022.10.09 |