|
| 1 | +package medium; |
| 2 | + |
| 3 | +public class RangeAddition { |
| 4 | + /**Previously AC'ed brute force solution results in TLE now.*/ |
| 5 | + public static int[] getModifiedArray_TLE(int length, int[][] updates) { |
| 6 | + int[] nums = new int[length]; |
| 7 | + int k = updates.length; |
| 8 | + for(int i = 0; i < k; i++){ |
| 9 | + int start = updates[i][0]; |
| 10 | + int end = updates[i][1]; |
| 11 | + int inc = updates[i][2]; |
| 12 | + for(int j = start; j <= end; j++){ |
| 13 | + nums[j] += inc; |
| 14 | + } |
| 15 | + } |
| 16 | + return nums; |
| 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 | + public static int[] getModifiedArray(int length, int[][] updates) { |
| 21 | + int[] nums = new int[length]; |
| 22 | + int k = updates.length; |
| 23 | + for (int i = 0; i < k; i++){ |
| 24 | + int start = updates[i][0]; |
| 25 | + int end = updates[i][1]; |
| 26 | + int inc = updates[i][2]; |
| 27 | + nums[start] += inc; |
| 28 | + if (end < length-1) nums[end+1] -= inc; |
| 29 | + } |
| 30 | + |
| 31 | + int sum = 0; |
| 32 | + for (int i = 0; i < length; i++){ |
| 33 | + sum += nums[i]; |
| 34 | + nums[i] = sum; |
| 35 | + } |
| 36 | + return nums; |
| 37 | + } |
| 38 | + |
| 39 | + public static void main(String...args){ |
| 40 | + /**5 |
| 41 | + [[1,3,2],[2,4,3],[0,2,-2]]*/ |
| 42 | + int length = 5; |
| 43 | + int[][] updates = new int[][]{ |
| 44 | + {1,3,2}, |
| 45 | + {2,4,3}, |
| 46 | + {0,2,-2}, |
| 47 | + }; |
| 48 | + int[] result = getModifiedArray(length, updates); |
| 49 | + for (int i : result) { |
| 50 | + System.out.print(i + "\t"); |
| 51 | + } |
| 52 | + } |
| 53 | +} |
0 commit comments