标签:
1 #include <iostream> 2 #include <vector> 3 using namespace std; 4 5 int main() 6 { 7 int m, n; 8 cin >> m >> n; 9 vector<vector<int> > value(m, vector<int>(n)); // 两个>用空格分开 10 for (int i = 0; i < m; i++){ 11 for (int j = 0; j < n; j++){ 12 int temp; 13 cin >> temp; 14 value[i].push_back(temp); 15 } 16 } 17 18 }
注意二维vector的行、列大小的确定
int row = value.size(); int col = value[0].size();
附《剑指offer》中“二维数组中的查找”一题
1 2 8 9 2 4 9 12 4 7 10 13 6 8 11 15
要找出7是否存在,把目标数跟该数组的右上角/左下角做对比,缩小查找的范围。
1 class Solution { 2 public: 3 bool Find(vector<vector<int> > array,int target) { 4 if (array.empty()) 5 return false; 6 int lenRow = array.size(); 7 int lenCol = array[0].size(); 8 9 int row = 0; 10 int col = lenCol - 1; 11 while (row < lenRow && col >= 0){ 12 if (array[row][col] == target) 13 return true; 14 else if (array[row][col] > target) 15 col--; 16 else 17 row++; 18 } 19 return false; 20 } 21 };
标签:
原文地址:http://www.cnblogs.com/cnblogsnearby/p/4611452.html