首页 > 解决方案 > 为什么只循环访问第一行?

问题描述

我将尝试从 2d 数组中查找元素,其中对每一行的元素进行排序。我使用 for 循环访问该行,然后在每一行中应用二进制搜索。但是 for 循环卡在第 1 行。

def searchMatrix(self, matrix, target) -> bool:
    m = len(matrix) 
    print(m)

    for i in range(m):  
        print(i)
        if len(matrix[i]) == 1:
            if matrix[i][0] == target:   
                return True
            else:
                return False
        else: 
            start = 0;
            end = len(matrix[0]) - 1
            while start <= end :
                    mid = round((start+end)/2)
                    if(matrix[i][mid] == target):
                        return True
                    elif matrix[i][mid] > target:
                        end = mid - 1
                    elif matrix[i][mid] < target:
                        start = start + 1        
            return False

我的输出:

3
0

但输出应该是

3 0 1 2

标签: python

解决方案


在您的循环中,所有条件都将导致一条return语句,因此该函数将在第一次迭代中退出。您可以删除所有return False并添加一个作为函数的最后一条语句:

def searchMatrix(self, matrix, target) -> bool:
    m = len(matrix) 
    print(m)

    for i in range(m):  
        print(i)
        if len(matrix[i]) == 1:
            if matrix[i][0] == target:   
                # Only exit the function if you find the target
                return True
        else: 
            start = 0;
            end = len(matrix[0]) - 1
            while start <= end :
                    mid = round((start+end)/2)
                    if(matrix[i][mid] == target):
                        # Only exit the function if you find the target
                        return True
                    elif matrix[i][mid] > target:
                        end = mid - 1
                    elif matrix[i][mid] < target:
                        start = start + 1

        # Otherwise, keep iterating

    # Since all rows were searched, exit the function
    return False

推荐阅读