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;
    
  • 相关阅读:
    2019-2020nowcoder牛客寒假基础2
    2019-2020nowcoder牛客寒假基础1
    CF1291
    Daily Codeforces
    2019ICPC 上海现场赛
    Codeforces Round #686 (Div. 3)
    Codeforces Round #685 (Div. 2)
    Educational Codeforces Round 98 (Rated for Div. 2)
    Codeforces Round #654 (Div. 2)
    Codeforces Round #683 (Div. 2, by Meet IT)
  • 原文地址:https://www.cnblogs.com/lightice/p/14495970.html
Copyright © 2011-2022 走看看