Given
A vertical area is an area of fixed-width extending infinitely along the y-axis (i.e., infinite height). The widest vertical area is the one with the maximum width.
Note that points on the edge of a vertical area are not considered included in the area.
n
points
on a 2D plane where points[i] = [xi, yi]
, Return the widest vertical area between two points such that no points are inside the area.A vertical area is an area of fixed-width extending infinitely along the y-axis (i.e., infinite height). The widest vertical area is the one with the maximum width.
Note that points on the edge of a vertical area are not considered included in the area.
Example 1:
Input: points = [[8,7],[9,9],[7,4],[9,7]]
Output: 1
Approach
Java
import java.util.Arrays;import java.util.Comparator;public class WidestVerticalArea {public static void main(String[] args) {int[][] points = { { 8, 7 }, { 9, 9 }, { 7, 4 }, { 9, 7 } };System.out.println(maxWidthOfVerticalArea(points));}static int maxWidthOfVerticalArea(int[][] points) {// sort the arrayArrays.sort(points, new Comparator<int[]>() {@Overridepublic int compare(int[] o1, int[] o2) {if (o1[0] == o2[0])return o1[1] - o2[1];return o1[0] - o2[0];}});int ans = 0;// iterate till the length of arrayfor (int i = 0; i < points.length - 1; i++) {// update answerans = Math.max(ans, points[i + 1][0] - points[i][0]);}return ans;}}
C++
#include <bits/stdc++.h>using namespace std;//comparator used for sortingstatic bool cmp(vector<int> &a, vector<int> &b){if (a[0] == b[0])return a[1] < b[1];return a[0] < b[0];}int maxWidthOfVerticalArea(vector<vector<int>> &points){//sort the arraysort(points.begin(), points.end(), cmp);int ans = 0;//iterate till the length of arrayfor (int i = 0; i < points.size() - 1; i++){//update answerans = max(ans, points[i + 1][0] - points[i][0]);}return ans;}int main(){vector<vector<int>> points = {{8, 7}, {9, 9}, {7, 4}, {9, 7}};cout << maxWidthOfVerticalArea(points);return 0;}
No comments:
Post a Comment