Java经典算法:范围附加

假设您有一个长度为n的数组,且数组的初始值为全0,并进行了k次更新操作。
每个操作都表示为一个三元组:[startIndex,endIndex,inc],它用inc递增子数组A [startIndex … endIndex]的每个元素(包括startIndex和endIndex)。
执行完所有k个操作后,返回修改后的数组。
例如,
输入:length = 5,更新= [[1,3,2],[2,4,3],[0,2,-2]]
输出:[-2,0,3,5,3 ]
Java解决方案:
public int[] getModifiedArray(int length, int[][] updates) {
int result[] = new int[length];
if(updatesnull || updates.length0)
return result;

//sort updates by starting index
Arrays.sort(updates, new Comparator<int[]>(){
    public int compare(int[] a, int [] b){
        return a[0]-b[0];
    }
});

ArrayList<int[]> list = new ArrayList<int[]>();

//create a heap sorted by ending index
PriorityQueue<Integer> queue = new PriorityQueue<Integer>(new Comparator<Integer>(){
    public int compare(Integer a, Integer b){
        return updates[a][1]-updates[b][1];
    }
});

int sum=0;
int j=0;
for(int i=0; i<length; i++){
    //substract value from sum when ending index is reached
    while(!queue.isEmpty() && updates[queue.peek()][1] < i){
        int top = queue.poll();
        sum -= updates[top][2];    
    }

    //add value to sum when starting index is reached
    while(j<updates.length && updates[j][0] <= i){
       sum = sum+updates[j][2];
       queue.offer(j);
       j++;
    }

    result[i]=sum;    
}

return result;}

最后,开发这么多年我也总结了一套学习Java的资料与面试题,如果你在技术上面想提升自己的话,可以关注我,私信发送领取资料或者在评论区留下自己的联系方式,有时间记得帮我点下转发让跟多的人看到哦。在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值