|
| 1 | +packagemedium; |
| 2 | + |
| 3 | +publicclassRangeAddition { |
| 4 | +/**Previously AC'ed brute force solution results in TLE now.*/ |
| 5 | +publicstaticint[]getModifiedArray_TLE(intlength,int[][]updates) { |
| 6 | +int[]nums =newint[length]; |
| 7 | +intk =updates.length; |
| 8 | +for(inti =0;i <k;i++){ |
| 9 | +intstart =updates[i][0]; |
| 10 | +intend =updates[i][1]; |
| 11 | +intinc =updates[i][2]; |
| 12 | +for(intj =start;j <=end;j++){ |
| 13 | +nums[j] +=inc; |
| 14 | + } |
| 15 | + } |
| 16 | +returnnums; |
| 17 | + } |
| 18 | + |
| 19 | +/**Looked at this post: https://discuss.leetcode.com/topic/49691/java-o-k-n-time-complexity-solution and one OJ official article: https://leetcode.com/articles/range-addition/*/ |
| 20 | +publicstaticint[]getModifiedArray(intlength,int[][]updates) { |
| 21 | +int[]nums =newint[length]; |
| 22 | +intk =updates.length; |
| 23 | +for (inti =0;i <k;i++){ |
| 24 | +intstart =updates[i][0]; |
| 25 | +intend =updates[i][1]; |
| 26 | +intinc =updates[i][2]; |
| 27 | +nums[start] +=inc; |
| 28 | +if (end <length-1)nums[end+1] -=inc; |
| 29 | + } |
| 30 | + |
| 31 | +intsum =0; |
| 32 | +for (inti =0;i <length;i++){ |
| 33 | +sum +=nums[i]; |
| 34 | +nums[i] =sum; |
| 35 | + } |
| 36 | +returnnums; |
| 37 | + } |
| 38 | + |
| 39 | +publicstaticvoidmain(String...args){ |
| 40 | +/**5 |
| 41 | + [[1,3,2],[2,4,3],[0,2,-2]]*/ |
| 42 | +intlength =5; |
| 43 | +int[][]updates =newint[][]{ |
| 44 | + {1,3,2}, |
| 45 | + {2,4,3}, |
| 46 | + {0,2,-2}, |
| 47 | + }; |
| 48 | +int[]result =getModifiedArray(length,updates); |
| 49 | +for (inti :result) { |
| 50 | +System.out.print(i +"\t"); |
| 51 | + } |
| 52 | + } |
| 53 | +} |