zoukankan      html  css  js  c++  java
  • 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 }
    —————————————————————————————————————行走在人猿的并行线——Laughing_Lz
  • 相关阅读:
    unity3D相机缓慢看向目标物体
    设计原则
    unity3D中GUI标题内文字滚动效果
    python3.6中安装PyQt报错
    codeforces 515B.Drazil and His Happy Friends
    HDU 1029 Ignatius and the Princess IV
    POJ 1052 Plato's Blocks
    Uva220 Othello
    uva201 Squares
    uva1587 Box
  • 原文地址:https://www.cnblogs.com/Laughing-Lz/p/5499579.html
Copyright © 2011-2022 走看看