Vulkan

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;
}

posted on 2014-04-28 22:00  Vulkan  阅读(92)  评论(0编辑  收藏  举报

导航