它给出了元素的位置及其值
在)
时间很少的 for 循环。
找到下面的代码:
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<vector<int>> a = { {2, 3, 4, 6}, {1, 98, 8, 22}, {12, 65, 1, 3}, {1, 7, 2, 12}};
vector<int> tmp;
//create 1-dimensional array to find the max element
for(int i=0;i<a.size();i++){
tmp.insert(tmp.end(),a[i].begin(),a[i].end());
}
//get the row and column location of the elment
int row = (max_element(tmp.begin(),tmp.end()) -tmp.begin())/a.size();
int col = (max_element(tmp.begin(),tmp.end()) -tmp.begin())%a.size();
// gets the value of the max element in O(n) time
int val = *max_element(tmp.begin(),tmp.end());
cout<<"Max element is located at:"<<(row+1)<<","<<(col+1)<<"and the value is "<<val<<endl;
return 0;
}