1 在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。(来自牛客网,剑指offer)
#include <iostream> #include <vector> std::vector<std::vector<int>> s; void init(int n) { int pos = n*2; for (int i = 0; i < n; ++i) { std::vector<int> tmp; for (int j = pos; j < pos + n; ++j) { tmp.push_back(j); } pos = pos + n; s.push_back(tmp); tmp.clear(); } } void print(std::vector<std::vector<int>> &s, int n) { for (int i=0; i < n; ++i) { for (auto itr:s[i]) { std::cout << itr << ","; } std::cout << " "; } } std::pair<int, int> find(std::vector<std::vector<int>> &s, int dst) { int line_cnt = s[0].size(); int col_cnt = s.size(); int low = 0; int high = col_cnt - 1; int nMid = (low + high) / 2; // 可能的列 int sus_col_pos = -1; while (low <= high) { nMid = (low + high) / 2; if (s[nMid][0] <= dst && s[nMid][s[nMid].size()-1] >= dst) { sus_col_pos = nMid; break; } else if (s[nMid][s[nMid].size()-1] < dst) { low = nMid + 1; } else { high = nMid - 1; } } //std::cout<< sus_col_pos; // 二分找到了列, 对行进行二分查找 low = 0; high = s[sus_col_pos].size()-1; int dst_pos = -1; while (low <= high) { int nMid = (low + high) / 2; if (s[sus_col_pos][nMid] == dst) { dst_pos = nMid; break; } else { if (s[sus_col_pos][nMid] > dst) { high = nMid - 1; } else { low = nMid + 1; } } } return std::make_pair(sus_col_pos, dst_pos); } int bi_search(int a[], int low, int high, int dst) { int nMid = (low + high) / 2; while(low <= high) { nMid = (low + high) / 2; if (a[nMid] == dst) { return nMid; } else { if (a[nMid] > dst) { high = nMid - 1; } else { low = nMid + 1; } } } return nMid; } std::ostream &operator<< (std::ostream &out, std::pair<int, int> &s) { //std::cout << "(" << s.first << "," << s.second << ")" << " "; out << "(" << s.first << "," << s.second << ")" << " "; return out; } int main() { init(5); print(s, 5); std::pair<int, int> res = find(s, 34); std::cout << res; // std::cout << find(s, 20).first; // int a[] = {2, 4, 6, 34, 90}; // std::cout << bi_search(a, 0, 4, 5); return 0; }
请实现一个函数,将一个字符串中的空格替换成“ % 20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
//注意如果输出的是%20d需要对%进行转义
//用Stl中的vector时间复杂度为:O(str.length());空间复杂度O(str.length+3*SpaceNum)
1 void ReplaceSpace( string strSrc,char *sOut) 2 { 3 vector<char> cOut; 4 const char *pStr = strSrc.data(); 5 while (*pStr != '