zoukankan      html  css  js  c++  java
  • LeetCode 750. Number Of Corner Rectangles

    原题链接在这里:https://leetcode.com/problems/number-of-corner-rectangles/

    题目:

    Given a grid where each entry is only 0 or 1, find the number of corner rectangles.

    corner rectangle is 4 distinct 1s on the grid that form an axis-aligned rectangle. Note that only the corners need to have the value 1. Also, all four 1s used must be distinct.

    Example 1:

    Input: grid = 
    [[1, 0, 0, 1, 0],
     [0, 0, 1, 0, 1],
     [0, 0, 0, 1, 0],
     [1, 0, 1, 0, 1]]
    Output: 1
    Explanation: There is only one corner rectangle, with corners grid[1][2], grid[1][4], grid[3][2], grid[3][4].

    Example 2:

    Input: grid = 
    [[1, 1, 1],
     [1, 1, 1],
     [1, 1, 1]]
    Output: 9
    Explanation: There are four 2x2 rectangles, four 2x3 and 3x2 rectangles, and one 3x3 rectangle.

    Example 3:

    Input: grid = 
    [[1, 1, 1, 1]]
    Output: 0
    Explanation: Rectangles must have four distinct corners.

    Note:

    1. The number of rows and columns of grid will each be in the range [1, 200].
    2. Each grid[i][j] will be either 0 or 1.
    3. The number of 1s in the grid will be at most 6000.

    题解:

    When there is a new row, within this row, row[c1] and row[c2] are both 1.

    Then number of newly constructed rectanges are number of previous rows having both exact same two columns mark as 1.

    To maintain number of two 1 on c1 and c2, use a hash function c1*200+c2. 

    Time Complexity: O(r*c^2). r = grid.length. c = grid[0].length.

    Space: O(c^2).

    AC Java: 

     1 class Solution {
     2     public int countCornerRectangles(int[][] grid) {
     3         int res = 0;
     4         HashMap<Integer, Integer> hm = new HashMap<>();
     5         for(int [] row : grid){
     6             for(int c1 = 0; c1<row.length; c1++){
     7                 if(row[c1] == 1){
     8                     for(int c2 = c1+1; c2<row.length; c2++){
     9                         if(row[c2] == 1){
    10                             int hash = c1*200+c2;
    11                             int count = hm.getOrDefault(hash, 0);
    12                             res += count;
    13                             hm.put(hash, count+1);
    14                         }
    15                     }
    16                 }
    17             }
    18         }
    19         
    20         return res;
    21     }
    22 }
  • 相关阅读:
    php 克隆和引用类
    php 抽象类、接口和构析方法
    php 面向对象之继承、多态和静态方法
    php封装练习
    php 面向对象之封装
    php 简单操作数据库
    php 练习
    用php输入表格内容
    php 指针遍历、预定义数组和常用函数
    php 数组定义、取值和遍历
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/11438546.html
Copyright © 2011-2022 走看看