美文网首页
和为S的连续正整数序列

和为S的连续正整数序列

作者: 小码弟 | 来源:发表于2018-10-24 09:15 被阅读0次

    描述:给定一个和S,找出和为S的连续序列,如9:[2,3,4], [4,5]

    分析:网上许多方法中,印象最深刻的是双指针法。两个指针限定区间的范围和大小。

    vector<vector<int>> CumSum(int S)
    {
      vector<vector<int>> res;
      vector<int>temp;
       int low = 1, high = 2;
       while(low<high)
       {
          // 计算当前区间的和
          int cur_sum = (low+high)*(high-low+1)/2;
          if(cur_sum == S)
          {
            for(int I = low; I<= high; I++)
              temp.push_back(i);
            res.push_back(temp);
            temp.clear();
            low++;
          }
         else
            if(cur_sum < S)
              // 区间和比S小,右边界右移,扩
              high++;
            else
              // 区间和比S大,左边界右移,缩
            low++;
      }
    return res;
    }
    

    相关文章

      网友评论

          本文标题:和为S的连续正整数序列

          本文链接:https://www.haomeiwen.com/subject/eelzzftx.html