4ms O(N+K) straightforward JAVA solution


  • 2
    L

    Logic example:

    1. If the array needs to be added with val=5 from index 3 to 10, then just add the value 5 on 3rd index and -5 on the 11th index of the result array.

    2. Then traverse from left to right to see what should be the value of the current array index i.e. the sum of all the elements in the result array formed in step 1.

    public int[] getModifiedArray(int length, int[][] updates) {
            
            int idx=0,k=updates.length, curr_sum = 0;
            int[] arr = new int[length];
            
            for(idx=0;idx<k;idx++){
                
                arr[updates[idx][0]] += updates[idx][2];
                
                if(updates[idx][1]<length-1){
                    arr[updates[idx][1]+1] -= updates[idx][2];
                }
            
            }
            
            for(idx=0;idx<length;idx++){
                curr_sum += arr[idx];
                arr[idx] = curr_sum;
            }
            
            return arr;
        }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.