zoukankan      html  css  js  c++  java
  • 算法题(1)

    1,已知一个二维数组从左到右递增,从上到下递增,求数target是否在数组中。
    (1)o(m*n)
    依次遍历查找出来。

    package day01;
    
    /**
     * @author wangpei
     * @version 创建时间:2017年1月17日 下午7:48:12 进行序列化
     */
    public class test {
    
        public boolean Find(int target, int[][] array) {
            for (int i = 0; i < array.length; i++) {
                for (int j = 0; j < array[i].length; j++)
                    if (target == array[i][j])
                        return true;
    
            }
            return false;
    
        }
    
        public static void main(String[] args) {
            test a = new test();
            int s[][] = { { 1, 3 }, { 3, 4 }, { 7, 8 } };
    
            System.out.println(a.Find(3, s));
        }
    
    }
    

    (2)从左下角进行遍历(向左依次递增,向上依次递减),若大于target,上移,小于,向右移。o(m+n)

     public boolean Find(int target, int [][] array) {
             int m=array.length-1;
             int n=0;//第0列
             while(m>=0&& n<=array[0].length-1){
                 if(array[m][n]>target)
                     m--;
                 else if(array[m][n]<target)
                     n++;
                 else
                     return true;
             }
             return false;
             }

    (3)因为每一行都是递增顺序,所以对每一行进行二分查找。o(nlogn)

         public boolean Find(int target, int [][] array) {
             for(int i=0;i<array.length;i++){
                 int low=0;
                 int high=array[0].length-1;
                 while(low<=high){
                     int mid=(low+high)/2;
                     if(array[i][mid]<target)
                         low=mid+1;
                     else if(array[i][mid]>target)
                         high=mid-1;
                     else
                         return true;
                 }
             }
             return false;
         }
    
  • 相关阅读:
    python 类
    hdu 5761 Rowe Bo 微分方程
    calendar 示例
    hdu 5753 Permutation Bo
    hdu 5752 Sqrt Bo
    finally 语句
    throws 和 throw
    python打开.pkl的文件并显示里面的内容
    Python 类变量,成员变量,静态变量,局部变量
    python 实例方法,类方法,静态方法,普通函数
  • 原文地址:https://www.cnblogs.com/wangxiaopei/p/8551259.html
Copyright © 2011-2022 走看看