部分文章内容为公开资料查询整理,原文出处可能未标注,如有侵权,请联系我,谢谢。邮箱地址:gnivor@163.com ►►►需要气球么?请点击我吧!

算法1:杨氏矩阵查找

杨氏矩阵查找

参考资料:

http://blog.csdn.net/jiyanfeng1/article/details/8189228
http://blog.sina.com.cn/s/blog_5b29caf701015tpg.html
http://www.cnblogs.com/avril/p/3294506.html

1 2  8   9
2 3  9  12
4 7 10 13
6 8 11 15

方法1 :从第一行最后一列开始比较。 时间复杂度O(m+n);

/**
 * 
 * 杨氏矩阵查找,即矩阵中的任意一个元素其右边和下边的元素都大于它,其左边和下边的元素都小于它
 *
 */
public class MatriFind {
    /**
     * 
     * @param a        要查找的矩阵
     * @param width 矩阵的宽
     * @param height 矩阵的高
     * @param num  要查找的元素
     */
    public void find(int a[][],int width,int height,int num){
        //使指针指向第一行的最后一个元素
        int xPos = width - 1;
        int yPos = 0;
        while(xPos >= 0 && yPos <= height - 1){
            if(a[xPos][yPos] == num){
                System.out.println("xPos:"+xPos+" yPos:"+yPos);
                return;
            }else if(a[xPos][yPos] > num){
                xPos--;
            }else{
                yPos++;
            }
        }
        System.out.println("没有找到!");
    }
    
    public static void main(String[] args) {
        MatriFind mf = new MatriFind();
        int matrix[][] = {
                {1,2,8,9},
                {2,4,9,12},
                {4,7,10,13},
                {6,8,11,15}
        };
        mf.find(matrix,matrix[0].length, matrix.length, 10);
    }
}

方法2:递归

方法3:分治+二分查找

posted @ 2015-05-04 15:13  流了个火  阅读(218)  评论(0)    收藏  举报
►►►需要气球么?请点击我吧!►►►
View My Stats