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

    题目为:在二维数组中,每一行从左到右递增,每一列都从上到下递增,写一个函数,输入这样一个数组和一个整数,判断这个数组中是不是有这个数字:

    思想:

    1.基本思想,最笨无非就是遍历这个二维数组嘛

    2.全部遍历的话,题目给的从左到右,从上到下的条件就没有用到,所以,全部遍历显然不合适

    先来一张图:


    图有点丑,意思到就行,来看,黑色箭头指向遍历的入口坐标,两个黑色箭头就说明,两种走的路径都是可以的,说一下,选择的理由,发现两个黑色箭头指向的坐标的值的或上或下或左或右都是有规律的,左下角的来说,上边的都比它小,右边的都比它大;不多说,直接上代码:

    //a为数组,rows为行数,cols为列数,number为查找数
    //         row为行号, cols为列号
    bool Find(int* a, int rows, int cols, int number)
    {
    	bool found = false;
    	if (a != nullptr && rows > 0 && cols > 0)
    	{
    		int row = rows - 1;
    		int col = 0;          //此两变量定位开始遍历的入口坐标
    		while (row < rows && col >= 0)
    		{
    			if (a[row*cols + col] > number)
    				--row;          //如果当前坐标值比number大,上走
    			else if (a[row*cols + col] < number)
    				++col;          //如果当前坐标值比number小,右走
    			else
    			{
    				found = true;
    				break;
    			}
    		}
    	}
    	return found;
    }
    这是左下角开始,再上一个右上角开始,内容差不多,不再过多描述,直接代码:

    bool Find(int* matrix, int rows, int columns, int number)
    {
        bool found = false;
    
        if(matrix != NULL && rows > 0 && columns > 0)
        {
            int row = 0;
            int column = columns - 1;
            while(row < rows && column >=0)
            {
                if(matrix[row * columns + column] == number)
                {
                    found = true;
                    break;
                }
                else if(matrix[row * columns + column] > number)
                    -- column;
                else
                    ++ row;
            }
        }
        return found;
    }



  • 相关阅读:
    Unix命令大全
    vs2008 与 IE8出现的兼容性问题
    Java 创建文件、文件夹以及临时文件
    如何修改Wamp中mysql默认空密码
    PAT 乙级真题 1003.数素数
    Tags support in htmlText flash as3
    DelphiXE4 FireMonkey 试玩记录,开发IOS应用 还是移植
    10 Great iphone App Review sites to Promote your Apps!
    HTML tags in textfield
    Delphi XE4 IOS 开发, "No eligible applications were found“
  • 原文地址:https://www.cnblogs.com/melons/p/5791859.html
Copyright © 2011-2022 走看看