假设您有一个长度为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解决方案:
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的资料与面试题,如果你在技术上面想提升自己的话,可以关注我,私信发送领取资料或者在评论区留下自己的联系方式,有时间记得帮我点下转发让跟多的人看到哦。