zoukankan      html  css  js  c++  java
  • 剑指offer(1)

    题目:

      在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。

      解答:

      方案一:从左下或者右上查找(代码以左下为例),目标大于当前数往右移动,小于往上移动。路径不可能出现凸字形。

      

    public class Solution {
        
        public static void main(String[] args) {
    		int number = 7;
    		int array[][] = new int [][] {{1,2,8,9},{2,4,9,12},{4,7,10,13},{6,8,11,15}};
    		Solution solution = new Solution();
    		boolean result = solution.Find(number,array);
    		System.out.println(result);
    		
    
    	}
        public boolean  Find(int target, int [][] array) {
    
            int i=array.length-1;
            int j=0;
            while(i>=0&&j<=array[0].length-1){
                if(array[i][j]>target){
                    i--;
                }else if(array[i][j]<target){
                    j++;
                }else{
                    return true;
                }
            }
            return false;
        }
    }
    

      方案二:当做一个长条数组,每行使用二分法查找

    public class Solution {
        
        public static void main(String[] args) {
            int number = 7;
            int array[][] = new int [][] {{1,2,8,9},{2,4,9,12},{4,7,10,13},{6,8,11,15}};
            Solution solution = new Solution();
            boolean result = solution.Find(number,array);
            System.out.println(result);
            
    
        }
        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 = (high+low)/2;
                    if(target<array[i][mid]){
                        high = mid-1;
                    }else if(target>array[i][mid]){
                        low = mid+1;
                    }else{
                        return true;
                    }
                }
            }
            return false;
        }
    }
  • 相关阅读:
    css文字选中效果
    使用HTML5来实现本地文件读取和写入
    web响应式图片的5种实现
    前端日志上报的新姿势“Beacon”
    lock文件_我们为什么需要 lock 文件
    本地电脑和远程电脑无法复制粘贴
    device supports x86 but apk only supports armeabi-v7a问题解决
    Android Studio中 安卓模拟器 联网
    Android Studio 配置Gradle
    Android连载1-自定义UI控件
  • 原文地址:https://www.cnblogs.com/figsprite/p/10440363.html
Copyright © 2011-2022 走看看