C++ 中將資料流表示為不相交區間


假設我們有一個整數資料流輸入,例如 a1, a2, ..., an, ..., 我們必須將到目前為止看到的數字總結為不相交區間的列表。例如,假設輸入整數為 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].

為了解決這個問題,我們將遵循以下步驟:

  • 建立一個名為 nums 的集合

  • 在初始化器中,設定 low := -inf 和 high := inf

  • 在接收 num 作為輸入的 addNum 方法中,將 num 插入到集合 nums 中

  • 在 get interval 方法中,執行以下操作:

  • 定義一個二維陣列 ret

  • it := 集合 nums 的起始元素

  • 當 it 在集合中時,執行:

    • x := it 的值

    • 如果 ret 為空或 ret 的最後一個元素的索引 1 的元素 + 1 < x,則:

      • 在 ret 的末尾插入對 {x, x}

    • 否則

      • 將 ret 的最後一個元素的索引 1 的元素加 1

    • it 指向下一個元素

  • 返回 ret

示例

讓我們看看下面的實現,以便更好地理解:

 線上演示

#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, ],]

更新於:2020年5月27日

瀏覽量:170

啟動您的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.