JZ-C-03

剑指offer第三题:二维数组中元素的查找

 1 //============================================================================
 2 // Name        : JZ-C-03.cpp
 3 // Author      : Laughing_Lz
 4 // Version     :
 5 // Copyright   : All Right Reserved
 6 // Description : Hello World in C++, Ansi-style
 7 //============================================================================
 8 
 9 #include <iostream>
10 using namespace std;
11 /**
12  *二维数组matrix中,每一行都从左到右递增排序, 每一列都从上到下递增排序
13  *这里将要查找的data和矩阵一直和右上角的元素进行比较。
14  */
15 bool FindData(int *matrix, int rows, int columns, int data) {
16     if (matrix != NULL && rows > 0 && columns > 0) {
17         int row = 0;
18         int column = columns - 1;
19         while (row <= rows - 1 && column >= 0) { //循环结束条件
20             if (matrix[row * columns + column] == data) {//二维数组在内存中占据连续的空间
21                 return true;
22             }
23             if (matrix[row * columns + column] < data) {
24                 row += 1;
25             } else if (matrix[row * columns + column] > data) {
26                 column -= 1;
27             }
28         }
29     }
30     return false;
31 
32 }
33 int main() {
34     int matrix[5][4] = { { 1, 2, 8, 9 }, { 2, 4, 9, 12 }, { 4, 7, 10, 13 }, { 6,
35             8, 11, 15 }, { 7, 10, 13, 18 } };
36     bool result = FindData((int *) matrix, 5, 4, 17); //二维数组,将指针array再转为整型指针?
37     cout << boolalpha << result << endl; //boolalpha:功能是把bool值显示为true或false。
38     return 0;
39 }

 

posted @ 2016-05-16 21:34  回看欧洲  阅读(150)  评论(0编辑  收藏  举报