Given n two-dimensional points in space, determine whether they lie on some vertical or horizontal line. If yes, print YES; otherwise, print NO.
Example:
Input: n = 5, arr = {{0, 1}, {0, 2}, {0, 3}, {0, 4}, {0, 5}}
Output: YES
Approach
Java
import java.util.HashSet;public class PointsOnLine {public static void main(String[] args) {int n = 5;int[][] arr = { { 0, 1 }, { 0, 2 }, { 0, 3 },{ 0, 4 }, { 0, 5 } };HashSet<Integer> xset = new HashSet<Integer>();HashSet<Integer> yset = new HashSet<Integer>();for (int i = 0; i < n; i++) {int a = arr[i][0], b = arr[i][1];xset.add(a);yset.add(b);}if (xset.size() == 1 || yset.size() == 1)System.out.println("YES");elseSystem.out.println("NO");}}
C++
#include <bits/stdc++.h>using namespace std;int main(){int n = 5;vector<vector<int>> arr = {{0, 1},{0, 2},{0, 3},{0, 4},{0, 5}};set<int> xset, yset;for (int i = 0; i < n; i++){int a = arr[i][0], b = arr[i][1];xset.insert(a);yset.insert(b);}if (xset.size() == 1 || yset.size() == 1)cout << "YES\n";elsecout << "NO\n";return 0;}
No comments:
Post a Comment