C++中的直線反射
假設我們在 2D 平面上有 n 個點,我們需要檢查是否存在一條與 y 軸平行的線可以對稱反射給定點,換句話說,檢查是否存在一條線,在所有點都沿給定線反射後,原始點集與反射點集相同。
因此,如果輸入為 points = [[1,1],[-1,1]]

那麼輸出將為真
為了解決這個問題,我們將按照以下步驟操作:-
定義一個集合 ok
n := points 的大小
minVal := 無窮大
maxVal := -無窮大
對於 initialize i := 0,當 i < n,更新(使 i 增加 1),執行以下操作:-
minVal := minVal 與 points[i, 0] 的最小值
maxVal := maxVal 與 points[i, 0] 的最大值
將 points[i] 插入 ok 中
mid := maxVal + minVal
對於 initialize i := 0,當 i < n,更新(使 i 增加 1),執行以下操作:-
x := points[i, 0]
y := points[i, 1]
x := mid - x
如果 { x, y } 不在 ok 中,那麼 -
返回 false
返回 true
示例
讓我們看一下以下實現以獲得更好的理解 -
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool isReflected(vector<vector<int<>& points) {
set<vector<int< > ok;
int n = points.size();
int minVal = INT_MAX;
int maxVal = INT_MIN;
for (int i = 0; i < n; i++) {
minVal = min(minVal, points[i][0]);
maxVal = max(maxVal, points[i][0]);
ok.insert(points[i]);
}
int mid = maxVal + minVal;
for (int i = 0; i < n; i++) {
int x = points[i][0];
int y = points[i][1];
x = mid - x;
if (!ok.count({ x, y }))
return false;
}
return true;
}
};
main(){
Solution ob;
vector<vector<int<> v = {{1,1},{-1,1}};
cout << (ob.isReflected(v));
}輸入
{{1,1},{-1,1}}輸出
1
廣告
資料結構
網路
關係型資料庫管理系統(RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP