二维数组中的查找
来源:互联网 发布:图文并茂用什么软件 编辑:程序博客网 时间:2024/06/05 10:50
package com.a.b;public class MatrixSearch {private static int[][] data = { { 1, 2, 8, 9 }, { 2, 4, 9, 12 },{ 4, 7, 10, 13 }, { 6, 8, 11, 15 } };private static int[] data2 = { 1, 2, 8, 9, 2, 4, 9, 12, 4, 7, 10, 13, 6, 8,11, 15 };public static void main(String[] args) {//注意测试功能、边界、特殊值int n = 5;// System.out.println(search(data, n));// System.out.println(search(data2, 4, 4, n));print(data2, 4, 4);}/** * 二维数组中查找 * @param matrix * @param n * @return */private static boolean search(int[][] matrix, int n) {// O(n^2)for (int i = 0; i < matrix.length; i++) {for (int j = 0; j < matrix[i].length; j++) {if (data[i][j] == n) {System.out.println("(" + i + "," + j + ")");return true;}}}return false;}/** * 行、列都升序的数组查找 * @param matrix * @param rows * @param columns * @param n * @return */private static boolean search(int[] matrix, int rows, int columns, int n) {boolean found = false;if (matrix != null && rows > 0 && columns > 0) {int row = 0, column = 3;while (row < rows && column >= 0) {System.out.println("(" + row + "," + column + ")="+ matrix[row * columns + column]);if (matrix[row * columns + column] == n) {found = true;break;} else if (n < matrix[row * columns + column]) {--column;} else {++row;}}}return found;}/** * 以二维数组的形式读取一维数组 * * @param matrix * @param rows * @param columns */private static void print(int[] matrix, int rows, int columns) {if (matrix != null && rows > 0 && columns > 0) {int row = 0, column = 0;while (row < rows && column < columns) {System.out.println("(" + row + "," + column + ")="+ matrix[row * columns + column]);if (++column >= columns) {column %= columns;++row;}}}}}
0 0
- 二维数组中的查找
- 二维数组中的查找
- 二维数组中的查找
- 二维数组中的查找
- 二维数组中的查找
- 二维数组中的查找
- 二维数组中的查找
- 二维数组中的查找
- 二维数组中的查找
- 二维数组中的查找
- 二维数组中的查找
- 二维数组中的查找
- 二维数组中的查找
- 二维数组中的查找
- 二维数组中的查找
- 二维数组中的查找
- 二维数组中的查找
- 二维数组中的查找
- zTree:JQuery树形插件使用示例
- iOS 之画线画图
- shell中的cut命令
- VB.NET的前世今生
- HDU_ACM-2005 第几天?
- 二维数组中的查找
- 乱写
- iOS 之贝塞尔曲线介绍
- subline Text 3 主题
- ffmpeg解码h264图像帧:av_parser_parse2()//解码不拷贝数据问题!
- Can’t connect to MySQL server有关linux tcp连接优化
- The Twin Towers+uva+简单dp(最长公共子序列)
- web页面跳转
- 定制iOS 7中的导航栏和状态栏