劍指offer】1.在一個二維數組中(每個一維數組的長度相同),每一行都按照從左到右遞增的順序排序,每一列都按照從上到下遞增的順序排序。

題目描述

在一個二維數組中(每個一維數組的長度相同),每一行都按照從左到右遞增的順序排序,每一列都按照從上到下遞增的順序排序。請完成一個函數,輸入這樣的一個二維數組和一個整數,判斷數組中是否含有該整數。

如圖:

只能從左下角或者從右上角入手,輸入的數大於當前數就往右走,小於當前的數就往上走

C++核心代碼:

class Solution {
public:
    bool Find(int target, vector<vector<int> > array) {
        int row = (int)array.size();//獲取行的長度
        int col = (int)array[0].size();//獲取列的長度
        int num=0;//這裏是從左下角下手的,初始化爲第一個
        if (row == 0 || col == 0)
			return false;
		if (target < array[0][0] || target > array[row - 1][col - 1])
			return false;
        for(int i=row-1;i>=0&&num<col;)//num<colCount是爲了防止數組越界
        {
            if(array[i][num]==target)
            {
                return true;
            }
            if(target>array[i][num])//如果輸入的數大於當前數就往右走num++ 進入下一個循環
            {
                num++;
                continue;
            }
            if(target<array[i][num])//如果輸入的數小於當前數就往上走num不變,進入下一個循環
            {
                i--;
                continue;
            }
            return false;
        }
        return false;
    }
};

C++完整代碼:

#include<stdio.h>
#include <iostream>
#include<stdlib.h>
#include<vector>
#include<string>
#include <algorithm>
using namespace std;
bool Find(int target, vector<vector<int> > array) {
	int row = (int)array.size();//獲取行的長度
	int col = (int)array[0].size();//獲取列的長度
	int num = 0;
	if (row == 0 || col == 0)
		return false;
	if (target < array[0][0] || target > array[row - 1][col - 1])
		return false;
	for (int i = row - 1; i >= 0 && num<col;)//num<colCount是爲了防止數組越界
	{
		if (array[i][num] == target)
		{
			return true;
		}
		if (target>array[i][num])
		{
			num++;
			continue;
		}
		if (target<array[i][num])
		{
			i--;
			continue;
		}
		return false;
	}
	return false;
}
int main()
{
	bool b;
	int r = 0, c = 0;
	cout << "Enter r: ";//規定二維數組行數
	cin >> r;
	cout << "Enter c: ";//規定二維數組列數
	cin >> c;
	vector<vector<int>> array;//定義二維數組
	vector<int>v;//定義一維數組
	array.clear();//將二維數組清空,或初始化(初始化代碼很簡單,不會可以百度)//也可不用這一步
	int temp = 0;
	for (int i = 0; i < r; i++)//輸入r*c的二維數組
	{
		v.clear();//子數組返回時要清除
		for (int j = 0; j < c; j++)
		{
			cin >> temp;
			v.push_back(temp);
		}
		array.push_back(v);
	}
	for (int i = 0; i < r; i++)//打印輸入的二維數組
	{
		for (int j = 0; j < c; j++)
		{
			cout << array[i][j] << " ";

		}
		printf("\n");
	}
	if (Find(5, array)) {
		cout << "true" << endl;
	}
	else {
		cout << "false" << endl;
	}
	system("pause");
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章