LeetCode 30天挑战 Day-21

LeetCode 30 days Challenge - Day 21

本系列将对LeetCode新推出的30天算法挑战进行总结记录,旨在记录学习成果、方便未来查阅,同时望为广大网友提供帮助。


Leftmost Column with at Least a One

(This problem is an interactive problem.)

A binary matrix means that all elements are 0 or 1. For each individual row of the matrix, this row is sorted in non-decreasing order.

Given a row-sorted binary matrix binaryMatrix, return leftmost column index(0-indexed) with at least a 1 in it. If such index doesn’t exist, return -1.

You can’t access the Binary Matrix directly. You may only access the matrix using a BinaryMatrix interface:

  • BinaryMatrix.get(x, y) returns the element of the matrix at index (x, y) (0-indexed).
  • BinaryMatrix.dimensions() returns a list of 2 elements [n, m], which means the matrix is n * m.

Submissions making more than 1000 calls to BinaryMatrix.get will be judged Wrong Answer. Also, any solutions that attempt to circumvent the judge will result in disqualification.

For custom testing purposes you’re given the binary matrix mat as input in the following four examples. You will not have access the binary matrix directly.

Example 1:

img

Input: mat = [[0,0],[1,1]]
Output: 0

Example 2:

img

Input: mat = [[0,0],[0,1]]
Output: 1

Example 3:

img

Input: mat = [[0,0],[0,0]]
Output: -1

Example 4:

img

Input: mat = [[0,0,0,1],[0,0,1,1],[0,1,1,1]]
Output: 1

Constraints:

  • 1 <= mat.length, mat[i].length <= 100
  • mat[i][j] is either 0 or 1.
  • mat[i] is sorted in a non-decreasing way.

Solution

题目要求分析:本题的解释较为生涩,简单来说:给定一个n x m的、只含有0或1的数组,找到其中含有1的、最左边的列,该数组每一行按照非降序排列。

解法:

暴力搜索复杂度是O(nm),采用二分降到O(nlogm)。

具体实现思想如下:

  1. 对每一列,使用变量flag(初始化为0)检测是否含有1:flag大于0则含有,反之不含有。
  2. 对每一行,使用二分搜索,且注意每一行中1总在0的右边出现(题示:每一行非降序排列),为找到最左边的列,遵守以下规则:
    1. 若mid列含有1,记录之,并且尝试寻找更左边的一列:r = mid
    2. 若mid列不含有1,则尝试寻找更右边的一列:l = mid + 1

最后,当l == r退出时,检测res是否为-1(初始化值),若仍为-1,则需要对第 l 列再次进行检测。

注:解释一下为什么只有为-1时需要检测:

  1. 退出时若res已经不为-1,则是通过规则1达到退出条件,说明正在尝试寻找“更左边”的一列,然而此时已经不存在更左边的合格列了,则无需检测。
  2. 若仍为-1,说明正在通过规则2尝试寻找合法列,退出循环后需要进行检测看看最后是否找到。

int leftMostColumnWithOne(BinaryMatrix &binaryMatrix) {
    int n = binaryMatrix.dimensions()[0], m = binaryMatrix.dimensions()[1];
    int l = 0, r = m - 1, res = -1, flag = 0;
    while (l < r) {
        int mid = (l + r) / 2;
        flag = 0;
        for (int i = 0; i < n; i++) flag += binaryMatrix.get(i, mid);
        if (flag) {res = mid; r = mid;}
        else l = mid + 1;
    }
    if (res == -1) {
        flag = 0;
        for (int i = 0; i < n; i++) flag += binaryMatrix.get(i, l);
    }
    return flag ? l : res;
}


传送门:Leftmost Column with at Least a One

2020/4 Karl

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值