本文主要是介绍Cracking The Coding Interview 9.6,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
//原文:
//
// Given a matrix in which each row and each column is sorted, write a method to find an element in it.
// 从最右一排,从上到下,小于右上角的元素则下降,大于右上角的元素则左移找;第一个相等的元素。
#include <iostream>
using namespace std;
int search(int **p, int sizex, int sizey, int key)
{int x = sizex;int y = 0;while(y<sizey && x>-1){if (key > p[y][x]){y ++;}else if(key < p[y][x]){x --;}else{cout<<"y "<<y<<" x "<<x<<endl;return p[y][x];}}return -1;
}int main()
{int sizea = 5;int sizeb = 6;int **p = new int *[sizea];for (int i = 0; i<sizea; i++){p[i] = new int[sizeb];}for (int i = 0; i<sizea; i++){for (int j = 0; j<sizeb; j++){p[i][j] = i*2 + j*3;}}cout<<endl;for (int i = 0; i<sizea; i++){for (int j = 0; j<sizeb; j++){cout<<p[i][j]<<" ";}cout<<endl;}cout<<search(p,sizea,sizeb,16);return 0;
}
这篇关于Cracking The Coding Interview 9.6的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!