1. 程式人生 > >LeetCode 598. Range Addition II (區域範圍內加法)

LeetCode 598. Range Addition II (區域範圍內加法)

res val 標簽 pub 所有 ive time mat nat

  Given an m * n matrix M initialized with all 0‘s and several update operations.

Operations are represented by a 2D array, and each operation is represented by an array with two positive integers a and b, which means M[i][j] should be added by one for all 0 <= i < a and 0 <= j < b.

You need to count and return the number of maximum integers in the matrix after performing all the operations.

Example 1:

Input: 
m = 3, n = 3
operations = [[2,2],[3,3]]
Output: 4
Explanation: 
Initially, M = 
[[0, 0, 0],
 [0, 0, 0],
 [0, 0, 0]]

After performing [2,2], M = 
[[1, 1, 0],
 [1, 1, 0],
 [0, 0, 0]]

After performing [3,3], M = 
[[2, 2, 1],
 [2, 2, 1],
 [1, 1, 1]]

So the maximum integer in M is 2, and there are four of it in M. So return 4.

Note:

  1. The range of m and n is [1,40000].
  2. The range of a is [1,m], and the range of b is [1,n].
  3. The range of operations size won‘t exceed 10,000.

題目標簽:Math

  這道題目給了我們一個 m*n 的matrix, 起初都是0, 根據operation給其中一部分區域加1。最後要return 最大值integer的個數。

我們可以從另一個角度出發,把這個題目轉化成圖形來理解,最大的值的區域就是所有operation的交集。如何找到這個區域呢,我們需要記錄一個min x 和min y 來求出交集的區域 = x*y, 相當於在求面積。

舉兩個例子來看一下:

Example 1:

  maxCount(3,3,[ [1,2], [2,1] ])

0 0 0 1 1 0 2 1 0

0 0 0 [1,2] -> 0 0 0 [2,1] -> 1 0 0 return 1;

0 0 0 0 0 0 0 0 0

  最小的 x = 1, 最小的 y = 1, 所以最小的交集是 0,0 這個坐標, 它的區域 = 1 * 1。

Example 2:

  maxCount(3,3,[ [1,3], [2,2] ])

0 0 0 1 1 1 2 2 1

0 0 0 [1,3] -> 0 0 0 [2,2] -> 1 1 0 return 2;

0 0 0 0 0 0 0 0 0

  最小的 x = 1, 最小的 y = 2, 所以最小的交集是 0,0 和 0,1 這兩個坐標, 它的區域 = 1 * 2。

  

Java Solution:

Runtime beats 77.83%

完成日期:06/17/2017

關鍵詞:matrix, 2d array

關鍵點:把題目轉換成圖形幫助理解

 1 public class Solution 
 2 {
 3     public int maxCount(int m, int n, int[][] ops) 
 4     {
 5         if(ops == null || ops.length == 0 )
 6             return m*n;
 7         
 8         int x = Integer.MAX_VALUE;
 9         int y = x;
10         
11         
12         
13         for(int i=0; i<ops.length; i++)
14         {
15             if(ops[i][0] < x)
16                 x = ops[i][0];
17             if(ops[i][1] < y)
18                 y = ops[i][1];
19 
20         }
21         
22         return x*y;
23     }
24 }

參考資料:

N / A

LeetCode 598. Range Addition II (區域範圍內加法)