zoukankan      html  css  js  c++  java
  • 二维数组中的查找

    从左下角开始

    public class Solution {
        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){
                    return true;
                }
                else if(target < array[i][j]){
                    i--;
                }else{
                    j++;
                }
            }
            return false;
        }
    }
    

    从右上角开始

    public class Solution {
        public boolean Find(int target, int [][] array) {
          	int i = 0;//初始化行的值
            int j = array[0].length-1;//初始化列的值
            while(i <= array.length-1 && j >= 0){
                if(array[i][j] == target){
                    return true;
                }
                else if(target < array[i][j]){
                    j--;
                }else{
                    i++;
                }
            }
            return false;
        }
    }
    

    我giao。。为何我代码跑不动,额。。是我把他默认成行列都相同了。。吐了吐了,每个一维数组长度相同不代表他是n*n的数组

     //首先判断数组不为空,否则直接返回false
                if(array!=null && array.length > 0 && array[0].length > 0){
                    int row = 0; //初始化行的值
                    int col = array[0].length - 1; //初始化列的值
                    //循环遍历判断,寻找target
                    while(row <= array.length-1 && col >= 0){
                        if(target == array[row][col]){
                            return true;
                        }else if(target < array[row][col]){
                            col--;
                        }else{
                            row++;
                        }
                    }
                }
                return false;
    
  • 相关阅读:
    铁轨
    POJ 2385 -- Apple Catching
    POJ 3258 -- River Hopscotch
    POJ 1469 -- COURSES (二分匹配)
    POJ 2349 -- Arctic Network
    最小生成树
    NOIP200703守望者的逃离
    NOIP200706字符串的展开
    POJ 1036 -- Gangsters
    POJ 1952 -- BUY LOW, BUY LOWER
  • 原文地址:https://www.cnblogs.com/lightice/p/14495970.html
Copyright © 2011-2022 走看看