算法挑战100天 - five(easy)

2020-09-01  本文已影响0人  holmes000

类别:数组

题目:https://leetcode-cn.com/problems/er-wei-shu-zu-zhong-de-cha-zhao-lcof/

我的解:时间 O(n2) 空间O(1)

 public boolean findNumberIn2DArray(int[][] matrix, int target) {
        Boolean flag = Boolean.FALSE;
        for (int i = 0; i < matrix.length; i++) {
            int low = 0;
            int high = matrix[i].length;
            for (int j = 0; j < matrix[i].length; j++) {
                int mid = (low + high) / 2;
                if (target > matrix[i][mid]) {
                    low = mid;
                } else {
                    high = mid;
                }
                if (matrix[i][mid] == target) {
                    flag = Boolean.TRUE;
                }
            }
        }
        return flag;
    }

最优解:时间 O(n) 空间O(1)

 public boolean findNumberIn2DArray2(int[][] matrix, int target) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return false;
        }
        int rows = matrix.length, columns = matrix[0].length;
        int row = 0, column = columns - 1;
        while (row < rows && column >= 0) {
            int num = matrix[row][column];
            if (num == target) {
                return true;
            } else if (num > target) {
                column--;
            } else {
                row++;
            }
        }
        return false;
    }

差异点:

1.没有利用数据特性,做判断;

上一篇下一篇

猜你喜欢

热点阅读