zoukankan      html  css  js  c++  java
  • 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.

    package leetcode;

    public class SearchA2DMatrix {
    //数组查找:1、排好序(二分查找的前提)2、二分查找!
    public static boolean searchMatrix(int[][] matrix, int target) {
          int m =0;
        while(m<=matrix.length-1){
            if(matrix[m][0]<=target&&matrix[m][matrix[0].length-1]>=target){
                 return binary(matrix[m],0,matrix[0].length-1,target);            
            }else
                m++;            
        }  
        return false;
        }

    public static boolean binary(int nums[] , int left,int right,int tar ){     //二分查找的一般算法
        while(right>=left){
        int mid = (right+left)/2;
        if(nums[mid] == tar)  return true;
        if(nums[mid] >tar) return binary(nums,left,mid-1,tar);
        return binary(nums,mid+1,right,tar);
        }
        return false;
    }

        public static void main(String[] args) {
            // TODO Auto-generated method stub

            int[][] a ={
              {1,   3,  5,  7},
              {10, 11, 16, 20},
              {23, 30, 34, 50}
              };
        System.out.print(searchMatrix(a,9));
        }

    }

    态度决定行为,行为决定习惯,习惯决定性格,性格决定命运
  • 相关阅读:
    【lwip】04内存管理
    微信小程序之获取当前位置经纬度以及地图显示
    Apache与Tomcat的区别和联系
    Jfinal中Db类的的使用
    利用GROUP_CONCAT和GROUP BY实现字段拼接
    实现easyui combobox中textField字段的拼接
    Jfinal数据库操作语句中占位符的使用
    Django项目部署到Apache服务器
    函数编程概念
    腾讯官网 样式初始化
  • 原文地址:https://www.cnblogs.com/neversayno/p/5290230.html
Copyright © 2011-2022 走看看