剑指Offer——01天
二维数组中的查找
- 由于矩阵是有序的,我们从矩阵的左下角来看,向上的递减的,向右是递增的,因此要从左下角开始寻找,当目标数字比左下角的数字大时右移,当目标数字小时上移
class Solution { public: bool Find(int target, vector<vector<int> > array) { int x,y,max_y; x=array.size()-1; y=0; max_y=array[0].size(); while(y<max_y&&x>=0) { if(target>array[x][y]) { y++; } else if(target<array[x][y]) { x--; } else return true; } return false; } };
替换空格
- 从后往前找空格,遇到空格先把后面的字符串往后移,再将空格位置替换成“%20”即可
class Solution { public: void replaceSpace(char *str,int length) { for(int i=length-1;i>=0;i--) { if(str[i]==' ') { for(int j=length-1;j>i;j--) { str[j+2]=str[j]; } str[i]='%'; str[i+1]='2'; str[i+2]='0'; length+=2; } } } };
从尾到头打印链表
- 将链表从头到尾扫一遍,利用STL每次插在最前面即可,注意head是有值的
class Solution { public: vector<int> printListFromTailToHead(ListNode* head) { vector <int> num; while(head!=NULL) { num.insert(num.begin(),head->val); head=head->next; } return num; } };
重建二叉树
- 递归思想
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) { int n = pre.size(); if(n==0) return NULL; TreeNode * root = new TreeNode(pre[0]); vector <int> left_pre,left_vin,right_pre,right_vin; int p=0; for(p;p<n;p++) { if(vin[p]==pre[0]) { break; } } for(int i=0;i<n;i++) { if(i<p) { left_pre.push_back(pre[i+1]); left_vin.push_back(vin[i]); } else if(i>p) { right_pre.push_back(pre[i]); right_vin.push_back(vin[i]); } } root->left = reConstructBinaryTree(left_pre,left_vin); root->right = reConstructBinaryTree(right_pre,right_vin); return root; } };
利用两个栈实现队列
- 不解释
class Solution { public: void push(int node) { stack1.push(node); } int pop() { int k; while(!stack1.empty()) { k = stack1.top(); stack1.pop(); stack2.push(k); } stack2.pop(); while(!stack2.empty()) { int m = stack2.top(); stack2.pop(); stack1.push(m); } return k; } private: stack<int> stack1; stack<int> stack2; };
旋转数组的最小数字
- 这是一道二分的变形题,若data[mid]>data[r],说明最小的元素在右边的区间里,l=mid+1;
- 反之,r--,因为可能存在这样的一个序列 111161
class Solution { public: int minNumberInRotateArray(vector<int> rotateArray) { int n = rotateArray.size(); if(n==0) return 0; else if(n==1) return rotateArray[0]; int l = 0; int r = n-1; int mid; while(l<=r) { mid = (l+r)/2; if(rotateArray[mid]>rotateArray[n-1]) l=mid+1; else r--; } return rotateArray[l]; } };