陣列演算法-差分陣列

_titleInfo發表於2024-05-29
// 差分陣列使用背景:區間元素同步增減
// 差分陣列:用來表示原始陣列中相鄰元素的差值,表示原陣列的變化。
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;
}

相關文章