zoukankan      html  css  js  c++  java
  • 剑指Offer_编程题_二维数组中的查找

    题目描述

    在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
     
     
    链接:https://www.nowcoder.com/questionTerminal/abc3fe2ce8e146608e868a70efebf62e?f=discussion
    来源:牛客网

    两种思路

    一种是:
    把每一行看成有序递增的数组,
    利用二分查找,
    通过遍历每一行得到答案,
    时间复杂度是nlogn
     
    public class Solution {
        public boolean Find(int [][] array,int target) {
             
            for(int i=0;i<array.length;i++){
                int low=0;
                int high=array[i].length-1;
                while(low<=high){
                    int mid=(low+high)/2;
                    if(target>array[i][mid])
                        low=mid+1;
                    else if(target<array[i][mid])
                        high=mid-1;
                    else
                        return true;
                }
            }
            return false;
     
        }
    }
     

     

    另外一种思路是:

    利用二维数组由上到下,由左到右递增的规律,
    那么选取右上角或者左下角的元素a[row][col]与target进行比较,
    当target小于元素a[row][col]时,那么target必定在元素a所在行的左边,
    即col--;
    当target大于元素a[row][col]时,那么target必定在元素a所在列的下边,
    即row++;
     
     
    public class Solution {
        public boolean Find(int [][] array,int target) {
            int row=0;
            int col=array[0].length-1;
            while(row<=array.length-1&&col>=0){
                if(target==array[row][col])
                    return true;
                else if(target>array[row][col])
                    row++;
                else
                    col--;
            }
            return false;
     
        }
    }
  • 相关阅读:
    nodejs向远程服务器发送post请求----融云Web SDK/客户端获取token
    Oauth2.0认证---授权码模式
    AngularJS---自定义指令
    Leetcode160-Intersection of Two Linked Lists-Easy
    Lintcode489-Convert Array List to Linked List-Easy
    Lintcode228-Middle of Linked List-Naive
    Lintcode174-Remove Nth Node From End of List-Easy
    Lintcode225-Find Node in Linked List-Naive
    Lintcode85-Insert Node in a Binary Search Tree-Easy
    Lintcode93-Balanced Binary Tree-Easy
  • 原文地址:https://www.cnblogs.com/liran123/p/12634659.html
Copyright © 2011-2022 走看看