สมมติว่าเรามีรายการที่เรียงลำดับของช่วงที่ไม่ปะติดปะต่อกัน แต่ละช่วงของช่วง[i] =[a, b] แทนชุดของตัวเลข x โดยที่ a <=x
เพื่อแก้ปัญหานี้ เราจะทำตามขั้นตอนเหล่านี้ -
- กำหนดวิธีการที่เรียกว่า manipulate2() ซึ่งจะใช้เมทริกซ์ a และอาร์เรย์ y
- x :=แถวสุดท้ายของเมทริกซ์ a จากนั้นลบแถวสุดท้ายออกจาก a
- z :=x
- x[0] :=y[1], z[1] :=y[0]
- ถ้า z[0] − z[1] ให้ใส่ z ลงใน a
- ถ้า x[0] − x[1] ให้ใส่ x ลงใน a
- วิธีหลักจะรับเมทริกซ์และอาร์เรย์ t
- กำหนดเมทริกซ์ ans และ n :=จำนวนแถวในเมทริกซ์ใน
- สำหรับ i ในช่วง 0 ถึง n –
- แทรก [i] ลงใน ans
- a :=แถวสุดท้ายของ a, b :=t
- ถ้า a[0]> b[0] ให้สลับ a กับ b
- ถ้า a และ b กำลังตัดกัน ให้เรียก manipulate2(ans, t)
- คืนสินค้า
ตัวอย่าง(C++)
ให้เราดูการใช้งานต่อไปนี้เพื่อความเข้าใจที่ดีขึ้น -
#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<vector<auto> > v){
cout << "[";
for(int i = 0; i<v.size(); i++){
cout << "[";
for(int j = 0; j <v[i].size(); j++){
cout << v[i][j] << ", ";
}
cout << "],";
}
cout << "]"<<endl;
}
class Solution {
public:
bool isIntersect(vector <int> a, vector <int> b){
return max(a[0], a[1]) >= min(b[0], b[1]);
}
void manipulate2(vector < vector <int> > &a, vector <int> y){
vector <int> x = a.back();
a.pop_back();
vector <int> z = x;
x[0] = y[1];
z[1] = y[0];
if(z[0] < z[1])a.push_back(z);
if(x[0] < x[1])a.push_back(x);
}
vector<vector<int>> removeInterval(vector<vector<int>>& in, vector<int>& t) {
vector < vector <int> > ans;
int n = in.size();
for(int i = 0; i < n; i++){
ans.push_back(in[i]);
vector <int> a;
vector <int> b;
a = ans.back();
b = t;
if(a[0]>b[0])swap(a, b);
if(isIntersect(a, b)){
manipulate2(ans, t);
}
}
return ans;
}
};
main(){
vector<int> v2 = {1,6};
vector<vector<int>> v1 = {{0,2},{3,4},{5,7}};
Solution ob;
print_vector(ob.removeInterval(v1, v2));
} อินพุต
[[0,2],[3,4],[5,7]] [1,6]
ผลลัพธ์
[[0, 1, ],[6, 7, ],]