• 【LeetCode】Search a 2D Matrix


    Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:

    • Integers in each row are sorted from left to right.
    • The first integer of each row is greater than the last integer of the previous row.

    For example,

    Consider the following matrix:

    [
      [1,   3,  5,  7],
      [10, 11, 16, 20],
      [23, 30, 34, 50]
    ]
    

    Given target = 3, return true.

    http://oj.leetcode.com/problems/search-a-2d-matrix/

    public class Solution {
        public boolean searchMatrix(int[][] matrix, int target) {
            int row=matrix.length;
            int col=matrix[0].length;
            if(row==0||col==0||matrix[0][0]>target||matrix[row-1][col-1]<target){
                return false;
            }
            int in =-1;
            for(int i=1;i<row;i++){
                if(matrix[i][0]>target){
                    in = i-1;
                    break;
                }
            }
            if(in==-1){
                in = row-1;
            }
            
            for(int x=0;x<col;x++){
                if(matrix[in][x]==target){
                    return true;
                }
            }
            
            return false;
            
        }
    }
  • 相关阅读:
    作业四 四则运算
    作业三
    作业二(3)
    作业二(2)
    作业二(1)
    作业一
    作业九
    每周更新学习进度表--第十一周
    每周更新学习进度表--第十周
    每周更新学习进度表--第九周
  • 原文地址:https://www.cnblogs.com/yixianyixian/p/3690196.html
Copyright © 2020-2023  润新知