LeetCode - 304. Range Sum Query 2D - Immutable

来源:互联网 发布:永井豪 知乎 编辑:程序博客网 时间:2024/05/16 11:56

前面已经做过一道Range Sum Query - Immutable的题目,当时我们采用的方法是新建一个数组存储nums中从0到当前index的元素的和,这样在sumRange方法中我们可以在O(1)的时间中得到结果,在题目要求的sumRange多次调用的情况下非常方便。

这里我们同样想要采用相似的方法,于是我们需要另外新建一个二维数组来存储和而不是单个的元素,2D情况下的sumRange分析如下:



为了方便,我们可以将这个二位数组扩展为[matrix.length + 1][matrix[0].length + 1],这样我们就可以采用同样的公式去计算而不需要进行边界的检查,所以sumRange函数的时间复杂度为O(1),而空间复杂度为O(mn),代码如下:

class MyStack {    Queue<Integer> queue;        public MyStack(){        queue = new LinkedList<Integer>();    }        // Push element x onto stack.    public void push(int x) {        queue.offer(x);        for(int i = 0; i < queue.size() - 1; i++){            queue.offer(queue.poll());        }    }    // Removes the element on top of the stack.    public void pop() {        queue.poll();    }    // Get the top element.    public int top() {        return queue.peek();    }    // Return whether the stack is empty.    public boolean empty() {        return queue.isEmpty();    }}


知识点:

1. 和上一道Range Sum Query - Immutable一样,都采用了预先计算然后存储的思想,这种方法虽然消耗了较多的memory,但是在time上做到了极快,在函数需要调用多次的时候可以采用这种思想

2. 其实这道题目和动态规划有共通之处,都是预先计算并且存储中间结果

0 0
原创粉丝点击