• LeetCode: 554. Brick Wall


    There is a brick wall in front of you. The wall is rectangular and has several rows of bricks. The bricks have the same height but different width. You want to draw a vertical line from the top to the bottom and cross the least bricks.

    The brick wall is represented by a list of rows. Each row is a list of integers representing the width of each brick in this row from left to right.

    If your line go through the edge of a brick, then the brick is not considered as crossed. You need to find out how to draw the line to cross the least bricks and return the number of crossed bricks.

    You cannot draw a line just along one of the two vertical edges of the wall, in which case the line will obviously cross no bricks.

    Example:

    Note:

    1. The width sum of bricks in different rows are the same and won't exceed INT_MAX.
    2. The number of bricks in each row is in range [1,10,000]. The height of wall is in range [1,10,000]. Total number of bricks of the wall won't exceed 20,000.

    我的解决方案:

    每个空隙处是以本组元素前面所有元素的叠加+0.1作为key的一个空隙,

    例如[1,2,3,4]2与3之间的空隙就是2.1,3与4之间的空隙就是6.1

    遍历每组数据,找到重复最多空隙的次数,

    以第一维数组的长度减去这个值就是需求的结果了

    源代码:

     1 package main
     2 
     3 import (
     4     "fmt"
     5 )
     6 
     7 var wall = [][]int{{1, 2, 2, 1}, {3, 1, 2}, {1, 3, 2}, {2, 4}, {3, 1, 2}, {1, 3, 1, 1}}
     8 
     9 func main() {
    10     fmt.Println(wall)
    11     leastBricks(wall)
    12 }
    13 
    14 func leastBricks(wall [][]int) int {
    15     m := make(map[int]int)
    16     len1 := len(wall)
    17     max := 0
    18     var len2 int
    19     var tKey int
    20     for i := 0; i < len1; i++ {
    21         len2 = len(wall[i]) - 1
    22         tKey = 0
    23         for j := 0; j < len2; j++ {
    24             tKey += wall[i][j]
    25 
    26             _, ok := m[tKey]
    27             if ok {
    28                 m[tKey]++
    29             } else {
    30                 m[tKey] = 1
    31             }
    32             if m[tKey] > max {
    33                 max = m[tKey]
    34             }
    35         }
    36     }
    37     return len1 - max
    38 }
  • 相关阅读:
    #ACsaber ——简单排序、字符串加空格、数组中的行 ~20.10.22
    #堆排序 20.09.27
    #并查集 20.09.25
    #卡特兰数 #抽屉原理 #Nim游戏 ——杂记
    #扩展欧几里得算法 ——线性同余方程 ~20.9.4
    #周测 7 —— 数的划分 、逆序对 、排座椅 、棋盘
    117. 占卜DIY
    116. 飞行员兄弟
    115.给树染色
    112.雷达设备
  • 原文地址:https://www.cnblogs.com/adoontheway/p/6727689.html
Copyright © 2020-2023  润新知