Notice
Recent Posts
Recent Comments
Today
Total
01-10 22:06
Link
๊ด€๋ฆฌ ๋ฉ”๋‰ด

Partially Committed

[LEETCODE] 1779.Find Nearest Point That Has the Same X or Y Coordinate ๋ณธ๋ฌธ

๐Ÿ”ฅ Algorithm || ๋ฌธ์ œํ’€์ด/PS

[LEETCODE] 1779.Find Nearest Point That Has the Same X or Y Coordinate

WonderJay 2022. 10. 11. 15:38
728x90
๋ฐ˜์‘ํ˜•
SMALL

https://leetcode.com/

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)

728x90
๋ฐ˜์‘ํ˜•
LIST
Comments