Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

สตรีมข้อมูลเป็นช่วงที่ไม่ปะติดปะต่อกันใน C++


สมมุติว่าเรามี data stream input ของ integers พวกนี้เป็น a1, a2, ..., an, ..., เราต้องสรุปตัวเลขที่เห็นเป็นรายการของ disjoint interval. ตัวอย่างเช่น สมมติว่าจำนวนเต็มอินพุตคือ 1, 3, 8, 2, 7, ... จากนั้นสรุปจะเป็น −

  • [1,1]

  • [1, 1], [3, 3]

  • [1, 1], [3, 3], [8, 8]

  • [1, 3], [8, 8]

  • [1, 3], [7, 8].

เพื่อแก้ปัญหานี้ เราจะทำตามขั้นตอนเหล่านี้ -

  • ทำชุดชื่อ หนุ่ม

  • ใน initializer ให้ตั้งค่า low :=-inf and high :=inf

  • จากเมธอด addNum ที่รับ num เป็นอินพุต ให้ใส่ num เข้าไปใน set nums

  • จากวิธี get interval ให้ทำดังนี้ -

  • กำหนดอาร์เรย์ 2D ret หนึ่งรายการ

  • มัน :=องค์ประกอบเริ่มต้นของชุดจำนวน

  • ขณะที่อยู่ในชุด ให้ทำ -

    • x :=คุณค่าของมัน

    • ถ้า ret ว่างเปล่าหรือองค์ประกอบที่ดัชนี 1 ขององค์ประกอบสุดท้ายของ ret + 1

      • ใส่คู่ { x, x } ที่ส่วนท้ายของ ret

    • มิฉะนั้น

      • เพิ่มองค์ประกอบที่มีอยู่ที่ดัชนี 1 ขององค์ประกอบสุดท้ายของ ret โดย 1

    • ไปที่องค์ประกอบถัดไป

  • รีเทิร์น

ตัวอย่าง

ให้เราดูการใช้งานต่อไปนี้เพื่อความเข้าใจที่ดีขึ้น -

#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 SummaryRanges {
   public:
   set <int> nums;
   int low, high;
   SummaryRanges() {
      low = INT_MAX;
      high = INT_MIN;
   }
   void addNum(int val) {
      nums.insert(val);
   }
   vector<vector<int>> getIntervals() {
      vector < vector <int> > ret;
      set <int> :: iterator it = nums.begin();
      while(it != nums.end()){
         int x = *it;
         if(ret.empty() || ret.back()[1] + 1 < x){
            ret.push_back({x, x});
         } else {
            ret.back()[1]++;
         }
         it++;
      }
      return ret;
   }
};
main(){
   SummaryRanges ob;
   ob.addNum(1);
   print_vector(ob.getIntervals());
   ob.addNum(3);
   print_vector(ob.getIntervals());
   ob.addNum(8);
   print_vector(ob.getIntervals());
   ob.addNum(2);
   print_vector(ob.getIntervals());
   ob.addNum(7);
   print_vector(ob.getIntervals());
}

อินพุต

Initialize the class, then insert one element at a time and see the intervals. So the elements are [1,3,8,2,7]

ผลลัพธ์

[[1, 1, ],]
[[1, 1, ],[3, 3, ],]
[[1, 1, ],[3, 3, ],[8, 8, ],]
[[1, 3, ],[8, 8, ],]
[[1, 3, ],[7, 8, ],]