Skip to content

Commit f792e52

Browse files
authored
Create Point Distances with Shared Coordinate.cpp
1 parent 2560811 commit f792e52

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
// https://binarysearch.com/problems/Point-Distances-with-Shared-Coordinate
2+
3+
int mindis(int i, vector<int>& v) {
4+
int lo = 0;
5+
int hi = v.size() - 1;
6+
int currdiff = INT_MAX;
7+
while (lo <= hi) {
8+
int mid = lo + (hi - lo) / 2;
9+
if (v[mid] < i) {
10+
currdiff = min(currdiff, (int)abs(v[mid] - i));
11+
lo = mid + 1;
12+
} else if (v[mid] > i) {
13+
currdiff = min(currdiff, (int)abs(v[mid] - i));
14+
hi = mid - 1;
15+
} else {
16+
if (mid - 1 >= 0) currdiff = min(currdiff, (int)abs(v[mid - 1] - i));
17+
if (mid + 1 < v.size()) currdiff = min(currdiff, (int)abs(v[mid + 1] - i));
18+
break;
19+
}
20+
}
21+
return currdiff;
22+
}
23+
vector<int> solve(vector<vector<int>>& points) {
24+
unordered_map<int, vector<int>> xtoy;
25+
unordered_map<int, vector<int>> ytox;
26+
for (auto point : points) {
27+
xtoy[point[0]].push_back(point[1]);
28+
ytox[point[1]].push_back(point[0]);
29+
}
30+
for (auto kv : xtoy) {
31+
sort(xtoy[kv.first].begin(), xtoy[kv.first].end());
32+
}
33+
for (auto kv : ytox) {
34+
sort(ytox[kv.first].begin(), ytox[kv.first].end());
35+
}
36+
vector<int> manhat;
37+
for (auto point : points) {
38+
manhat.push_back(min(mindis(point[1], xtoy[point[0]]), mindis(point[0], ytox[point[1]])));
39+
}
40+
return manhat;
41+
}

0 commit comments

Comments
 (0)