数组算法-差分数组

// 差分数组使用背景:区间元素同步增减
// 差分数组:用来表示原始数组中相邻元素的差值,表示原数组的变化。
class ex_diff{
    private:
        vector<int> diff;
    public:
        ex_diff(vector<int> nums){
            /** 求diff[]
             * diff[i] = nums[i],i==0
             * diff[i] = nums[i] - nums[i-1],i>=1
            */
            diff.resize(nums.size());
            diff[0] = nums[0];
            for(int i=1;i<nums.size();i++){
                diff[i] = nums[i] - nums[i-1];
            }
        }

        vector<int> GetSourceArrByDiff(vector<int> diff){
            /** 根据diff[]倒推原数组
             * nums[i] = diff[i],i==0
             * nums[i] = diff[i] + nums[i-1],i>=1
            */
            vector<int> t(diff.size());
            t[0] = diff[0];
            for(int i=1;i<diff.size();i++){
                t[i] = t[i-1]+diff[i];
            }
            return t;
        }

        /** 对原数组区间[l,r]内的元素统一加val时:
         * 1.只需要对差分数组diff[l]+=val,对diff[r+1]-=val;
         * 2.再根据diff[]反推出原数组
        */
        vector<int> plus_onArea(int l,int r,int val){
            diff[l] += val;
            if(r+1< sizeof(diff)/sizeof(diff[0])){
                diff[r+1] -= val;
            }
            return GetSourceArrByDiff(diff);
        }

        void test_ex_diff(){
            for(auto it:diff){
                cout << it << " ";
            }
            cout << endl;
            vector<int> ans = GetSourceArrByDiff(diff);
            for(auto it:ans){
                cout << it << " ";
            }
            cout << endl;
        }
};
int main(){

    vector<int> nums{1,3,5,7,9};
    vector<int> t = ex_diff(nums).plus_onArea(1,3,10);
    for(auto it:t){
        cout << it << " ";
    }

    return 0;
}

 

posted @ 2024-05-29 19:21  _titleInfo  阅读(5)  评论(0编辑  收藏  举报
//雪花飘落效果