java+queue+<integer>_Java经典算法:范围附加

假设您有一个长度为n的数组,且数组的初始值为全0,并进行了k次更新操作。

1c70b486e8969d00f5b1573f416b48e0.png

每个操作都表示为一个三元组:[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解决方案:

publicint[] getModifiedArray(intlength, int[][] updates) {

intresult[] = newint[length];

if(updates==null|| updates.length==0)

returnresult;

//sort updates by starting index

Arrays.sort(updates, new Comparator(){

publicintcompare(int[] a, int [] b){

returna[0]-b[0];

}

});

ArrayList list = new ArrayList();

//create a heap sorted by ending index

PriorityQueue queue = new PriorityQueue(new Comparator(){

publicintcompare(Integer a, Integer b){

returnupdates[a][1]-updates[b][1];

intsum=0;

intj=0;

for(inti=0; i

//substract value from sum when ending index is reached

while(!queue.isEmpty() && updates[queue.peek()][1] < i){

inttop = queue.poll();

sum -= updates[top][2];

//add value to sum when starting index is reached

while(j

sum = sum+updates[j][2];

queue.offer(j);

j++;

result[i]=sum;

}

returnresult;}

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

2ac8c10fb7c6ddbffeaef4074807b04d.png

48520c9260fbe7e0e7672b2a8fa6577b.png

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值