303. 区域和检索 - 数组不可变
题目:
思路:
【1】利用左右汇总数据集的方式(当然做完后你会发现单个数据集其实也是可以的,毕竟一开始我以为是乘积)
代码展示:
对数据集的优化:
//时间7 ms击败100% //内存44.1 MB击败75.81% class NumArray { private int[] sums; public NumArray(int[] nums) { sums = new int[nums.length + 1]; for (int i = 1; i <= nums.length; i++) { sums[i] = sums[i - 1] + nums[i - 1]; } } public int sumRange(int i, int j) { return sums[j + 1] - sums[i]; } }
利用左右汇总数据集的方式:
//时间7 ms击败100% //内存44.5 MB击败30.47% class NumArray { int[] left_nums; int[] right_nums; int sum; public NumArray(int[] nums) { left_nums = new int[nums.length]; right_nums = new int[nums.length]; for (int i = 0; i < nums.length; i++){ sum += nums[i]; } for (int i = 1; i < nums.length; i++){ left_nums[i] = left_nums[i - 1] + nums[i-1]; } for (int i = nums.length - 2; i >= 0; i--){ right_nums[i] = right_nums[i + 1] + nums[i+1]; } } public int sumRange(int left, int right) { return sum - left_nums[left] - right_nums[right]; } } /** * Your NumArray object will be instantiated and called as such: * NumArray obj = new NumArray(nums); * int param_1 = obj.sumRange(left,right); */