面试笔试杂项积累-leetcode 301-305

来源:互联网 发布:centos开机启动命令 编辑:程序博客网 时间:2024/05/20 04:12

303.303-Range Sum Query - Immutable-Difficulty: Easy

Given an integer array nums, find the sum of the elements between indicesi and j (ij), inclusive.

Example:

Given nums = [-2, 0, 3, -5, 2, -1]sumRange(0, 2) -> 1sumRange(2, 5) -> -1sumRange(0, 5) -> -3

Note:

  1. You may assume that the array does not change.
  2. There are many calls to sumRange function.

思路

写一个能返回范围和的函数

开始写的是每次都在该范围遍历加和,结果超时,确实是一个浪费的方法

好方法就是,在构造函数里存一个所有数到当前位置之和的数组sum,结果求【n-m】d的范围时就是sum[m]-sum[n-1],n为0时返回sum[m]即可

public class NumArray {            int[] sum;//= new int[];        public NumArray(int[] nums)//先把和都求出来,最后用的时候减去前面的就好        {                       if (nums.Length <= 0)                return; sum = new int[nums.Length];            sum[0] = nums[0];            for (int i = 1; i < nums.Length; i++)            {                sum[i] = sum[i - 1] + nums[i];            }        }        public int SumRange(int i, int j)        {            return i > 0 ? sum[j] - sum[i - 1] : sum[j];        }}// Your NumArray object will be instantiated and called as such:// NumArray numArray = new NumArray(nums);// numArray.SumRange(0, 1);// numArray.SumRange(1, 2);

304.304-Range Sum Query 2D - Immutable-Difficulty: Medium

Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper left corner (row1,col1) and lower right corner (row2, col2).

Range Sum Query 2D
The above rectangle (with the red border) is defined by (row1, col1) = (2, 1) and (row2, col2) =(4, 3), which contains sum = 8.

Example:

Given matrix = [  [3, 0, 1, 4, 2],  [5, 6, 3, 2, 1],  [1, 2, 0, 1, 5],  [4, 1, 0, 1, 7],  [1, 0, 3, 0, 5]]sumRegion(2, 1, 4, 3) -> 8sumRegion(1, 1, 2, 2) -> 11sumRegion(1, 2, 2, 4) -> 12

Note:

  1. You may assume that the matrix does not change.
  2. There are many calls to sumRegion function.
  3. You may assume that row1 ≤ row2 andcol1 ≤ col2.

思路

上题303的增强版,

每行都如上处理,到最后求和把所有列加起来即可


public class NumMatrix {    int[,] sum;        public NumMatrix(int[,] matrix)        {            sum = new int[matrix.GetLength(0), matrix.GetLength(1)];            for (int i = 0; i < matrix.GetLength(0); i++)           {                  sum[i, 0] = matrix[i, 0];               for (int j = 1; j < matrix.GetLength(1); j++)                {                    sum[i, j] = sum[i, j - 1] + matrix[i, j];                }           }        }        public int SumRegion(int row1, int col1, int row2, int col2)        {            int fin = 0;            for (int i = 0; i < row2-row1+1; i++)            {                fin += sum[row1 + i, col2] - (col1 > 0 ? sum[row1 + i, col1 - 1] : 0);            }                  return fin;        }}// Your NumMatrix object will be instantiated and called as such:// NumMatrix numMatrix = new NumMatrix(matrix);// numMatrix.SumRegion(0, 1, 2, 3);// numMatrix.SumRegion(1, 2, 3, 4);






0 0
原创粉丝点击