剑指offer(C++版本)
剑指offer(c++版本)
- 二维数组查找
- 替换空格
- 从尾到头打印链表
- 重建二叉树
- 用两个栈实现队列
- 旋转数组的最小数字
- 斐波那契数列
- 跳台阶
- 矩阵覆盖
- 二进制1的个数
- 数值的整数次方
- 调整数组顺序使奇数位于偶数前面
- 链表中倒数第k个结点
- 反转链表
- 合并两个排序的链表
- 树的子结构
- 二叉树的镜像
- 顺时针打印矩阵
- 包含Min函数的栈
- 栈的压入、弹出序列
- 从上往下打印二叉树
- 二叉树搜索的后序遍历序列
- 二叉树中和为某一值的路径
- 复杂链表的复制
- 二叉搜索树与双向链表
- 字符串的排列
- 数组中出现次数超过一半的数字
- 最小的K个数
- 连续子数组的最大和
- 整数中1出现的次数
- 把数组排成最小的数
- 丑数
- 第一次只出现一次的字符
- 数组中的逆序对
- 两个链表的第一个公共结点
- 数字在排序数组中出现的次数
- 二叉树的深度
- 平衡二叉树
- 数组中只出现一次的数字
- 和为S的连续正数序列
- 和为S的两个数字
- 左旋转字符串
- 翻转单词顺序列
- 扑克牌顺子
- 孩子们的游戏(圆圈中最后剩下的数)
- 求1+2+3…+n
- 不用加减乘除做加法
- 把字符串转换成整数
- 数组中重复的数字
- 构建乘积数组
- 正则表达式匹配
- 表示数值的字符串
- 字符流中第一个不重复的字符
- 链表中环的入口结点
- 删除链表中重复的结点
- 二叉树的下一个结点
- 对称二叉树
- 按之字形顺序打印二叉树
- 把二叉树打印成多行
- 序列化二叉树
- 二叉搜索树的第k个结点
- 数据流中的中位数
- 滑动窗口的最大值
- 矩阵中的路径
- 机器人的运动范围
二维数组查找
在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
class Solution {
public:bool Find(int target, vector<vector<int> > array) {int row = array.size();int col = array[0].size();for(int i=0;i<row;i++){for(int j=0;j<col;j++){if(target==array[i][j]){return true;}}}return false;}
};
替换空格
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。注:"a"和’a’的区别,前者是字符串,后者是字符。
class Solution {
public:void replaceSpace(char *str,int length) {int i=0;while(str[i]!='\0'){if(str[i]==' '){for(int j=length-1;j>i;j--){str[j+2]=str[j];}str[i+2]='0';str[i+1]='2';str[i]='%';length+=2;i=i+2;}else{i++;}}}
};
从尾到头打印链表
输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
class Solution {
public:vector<int> printListFromTailToHead(ListNode* head) {ListNode* p=head;vector<int> result;while(p!=NULL){result.push_back(p->val);p=p->next;}reverse(result.begin(),result.end());return result;}
};
重建二叉树
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
/*** 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 len=vin.size();if (len==0)return NULL;vector<int> left_pre,right_pre,left_vin,right_vin;TreeNode* head = new TreeNode(pre[0]);int gen = 0;for(int i=0;i<len;i++){if(vin[i]==pre[0]){gen = i;break;}}for(int i=0;i<gen;i++){left_pre.push_back(pre[i+1]);left_vin.push_back(vin[i]);}for(int i=gen+1;i<len;i++){right_pre.push_back(pre[i]);right_vin.push_back(vin[i]);}head->left = reConstructBinaryTree(left_pre,left_vin);head->right = reConstructBinaryTree(right_pre,right_vin);return head;}
};
用两个栈实现队列
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
class Solution
{
public:void push(int node) {stack1.push(node);}int pop() {int value;if (stack2.size()>0){value = stack2.top();stack2.pop();}else if (stack1.size()>0){while(stack1.size()>0){int element = stack1.top();stack2.push(element);stack1.pop();}value = stack2.top();stack2.pop();}return value;}
旋转数组的最小数字
把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。 输入一个非减排序的数组的一个旋转,输出旋转数组的最小元素。 例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。 NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。
class Solution {
public:int minNumberInRotateArray(vector<int> rotateArray) {/*if(rotateArray.size()== 0){return 0;}else{int i = 0;while(rotateArray[i]> rotateArray[i+1]){i++;}vector<int> resultArray;int m = 0;for(int j=i+1;j<rotateArray.size();j++){resultArray[m++] = rotateArray[j];}for(int j=0;j<=i;j++){resultArray[m++] = rotateArray[j];}}}*/sort(rotateArray.begin(),rotateArray.end());return rotateArray[0];}
};
斐波那契数列
大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0)。
class Solution {
public:int Fibonacci(int n) {if(n==0)return 0;else if(n==1)return 1;else{int a = 0;int b = 1;int temp;while(n>1){temp = a;a = b;b = temp+b;n--;}return b;}}
};
跳台阶
一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法(先后次序不同算不同的结果)。
class Solution {
public:int jumpFloor(int number) {if(number==1)return 1;else if(number==2)return 2;else{return jumpFloor(number-1)+jumpFloor(number-2);}}
};
矩阵覆盖
我们可以用21的小矩形横着或者竖着去覆盖更大的矩形。请问用n个21的小矩形无重叠地覆盖一个2*n的大矩形,总共有多少种方法?
# -*- coding:utf-8 -*-
class Solution {
public:int rectCover(int number) {if(number==0)return 0;else if(number==1)return 1;else if(number==2)return 2;else{int a = 1;int b = 2;int temp;while(number>2){temp = a;a = b;b = temp+b;number--;}return b;}}
};
二进制1的个数
输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。
class Solution {
public:int NumberOf1(int n) {int result = 0;unsigned int flag = 1;while(flag){if(n&flag)result++;flag = flag<<1;}return result;}
};
数值的整数次方
给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。
class Solution {
public:double Power(double base, int exponent) {double result=1;if(exponent>0){for(int i=1;i<=exponent;i++){result = result*base;}}else if(exponent==0){return 1;}else{base=1/base;for(int i=1;i<=abs(exponent);i++){result = result*base;}}return result;}
};
调整数组顺序使奇数位于偶数前面
输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前半部分,所有的偶数位于数组的后半部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变。
class Solution {
public:void reOrderArray(vector<int> &array) {vector<int> result_even, result_odd;for(int i=0;i<array.size();i++){if(array[i]%2==0){result_even.push_back(array[i]);}else{result_odd.push_back(array[i]);}}result_odd.insert(result_odd.end(),result_even.begin(),result_even.end());array = result_odd;}
};
链表中倒数第k个结点
输入一个链表,输出该链表中倒数第k个结点。
/*
struct ListNode {int val;struct ListNode *next;ListNode(int x) :val(x), next(NULL) {}
};*/
class Solution {
public:ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {ListNode* p;p=pListHead;for(unsigned int i=0;i!=k;i++){if(p==NULL)return NULL;elsep = p->next;}while(p!=NULL){p=p->next;pListHead = pListHead->next;}return pListHead;}
};
反转链表
输入一个链表,反转链表后,输出新链表的表头。
/*
struct ListNode {int val;struct ListNode *next;ListNode(int x) :val(x), next(NULL) {}
};*/
class Solution {
public:ListNode* ReverseList(ListNode* pHead) {ListNode* last;ListNode* temp;last = NULL;while(pHead!=NULL){temp = pHead->next;pHead->next = last;last = pHead;pHead = temp;}return last;}
};
合并两个排序的链表
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
/*
struct ListNode {int val;struct ListNode *next;ListNode(int x) :val(x), next(NULL) {}
};*/
class Solution {
public:ListNode* Merge(ListNode* pHead1, ListNode* pHead2){ListNode* phead = new ListNode(0);ListNode* list_new = phead;while(pHead1 || pHead2){if(pHead1==NULL){list_new->next=pHead2;break;}else if(pHead2==NULL){list_new->next = pHead1;break;}if((pHead1->val)>(pHead2->val)){list_new->next = pHead2;list_new = list_new->next;pHead2=pHead2->next;}else{list_new->next = pHead1;list_new = list_new->next;pHead1=pHead1->next;}}return phead->next;}
};
树的子结构
输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)
/*
struct TreeNode {int val;struct TreeNode *left;struct TreeNode *right;TreeNode(int x) :val(x), left(NULL), right(NULL) {}
};*/
class Solution {
public:bool HasSubtree(TreeNode* pRoot1, TreeNode* pRoot2){if(!pRoot1)return false;if(!pRoot2)return false;return (dfs(pRoot1,pRoot2)||HasSubtree(pRoot1->left,pRoot2)||HasSubtree(pRoot1->right,pRoot2));}
private:bool dfs(TreeNode* R1, TreeNode* R2){if(!R2)return true;if(!R1)return false;if(R1->val!=R2->val)return false;return dfs(R1->left,R2->left) && dfs(R1->right,R2->right);}
};
二叉树的镜像
操作给定的二叉树,将其变换为源二叉树的镜像。
/*
struct TreeNode {int val;struct TreeNode *left;struct TreeNode *right;TreeNode(int x) :val(x), left(NULL), right(NULL) {}
};*/
class Solution {
public:void Mirror(TreeNode *pRoot) {if (!pRoot)return;TreeNode *temp;temp = pRoot->left;pRoot->left = pRoot->right;pRoot->right = temp;Mirror(pRoot->right);Mirror(pRoot->left);}
};
顺时针打印矩阵
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下4 X 4矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.
class Solution {
public:vector<int> printMatrix(vector<vector<int> > matrix) {int cir = 0;int row = matrix.size();int col = matrix[0].size();vector<int> ans;while(row>2*cir && col>2*cir){//上面for(int i=cir;i<=col-cir-1;i++)ans.push_back(matrix[cir][i]);//右面if(cir<row-cir-1){for(int i=cir+1;i<=row-cir-1;i++)ans.push_back(matrix[i][col-cir-1]);}//下面if(col-cir-1>cir && row-1-cir>cir){for(int i=col-cir-2;i>=cir;i--)ans.push_back(matrix[row-1-cir][i]);}//左面if(cir<col-cir-1 && cir<row-cir-2){for(int i = row-cir-2;i>=cir+1;i--)ans.push_back(matrix[i][cir]);}cir++;}return ans;}
};
包含Min函数的栈
定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
class Solution {
public:void push(int value) {stack1.push(value);if(stackmin.empty())stackmin.push(value);else if (stackmin.top()<value)stackmin.push(stackmin.top());elsestackmin.push(value);}void pop() {stack1.pop();stackmin.pop();}int top() {return stack1.top();}int min() {return stackmin.top();}
private:stack<int> stack1;stack<int> stackmin;
};
栈的压入、弹出序列
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)
class Solution {
public:bool IsPopOrder(vector<int> pushV,vector<int> popV) {stack<int> st;for(int i=0;i<pushV.size();i++){st.push(pushV[i]);while(!st.empty() && st.top()==popV[0]){st.pop();popV.erase(popV.begin());}}if(st.empty())return true;elsereturn false;}
};
从上往下打印二叉树
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
/*
struct TreeNode {int val;struct TreeNode *left;struct TreeNode *right;TreeNode(int x) :val(x), left(NULL), right(NULL) {}
};*/
class Solution {
public:vector<int> PrintFromTopToBottom(TreeNode* root) {vector<int> result;queue<TreeNode*> Q;TreeNode* fr;if(root==NULL) return result;Q.push(root);while(!Q.empty()){fr = Q.front();result.push_back(fr->val);if(fr->left!=NULL)Q.push(fr->left);if(fr->right!=NULL)Q.push(fr->right);Q.pop();}return result;}
};
二叉树搜索的后序遍历序列
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
class Solution {
public:bool VerifySquenceOfBST(vector<int> sequence) {if(sequence.empty())return false;int index;int begin = 0;int end = sequence.size()-1;int root = sequence[end];for(index = begin;index<end;index++)if(sequence[index]>root)break;for(int j = index;index<end;index++)if(sequence[index]<root)return false;bool left = true;vector<int> left_sq(sequence.begin(),sequence.begin()+index);if(index>begin)left = VerifySquenceOfBST(left_sq);bool right = true;vector<int> right_sq(sequence.begin()+index+1,sequence.end());if(index<end-1)right = VerifySquenceOfBST(right_sq);return left&&right;}
};
二叉树中和为某一值的路径
输入一颗二叉树的跟节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)
/*
struct TreeNode {int val;struct TreeNode *left;struct TreeNode *right;TreeNode(int x) :val(x), left(NULL), right(NULL) {}
};*/
class Solution {
public:vector<vector<int>> result;vector<int> temp;vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {if(root==NULL)return result;temp.push_back(root->val);if(expectNumber-root->val==0 && root->left==NULL && root->right==NULL)result.push_back(temp);FindPath(root->left,expectNumber-root->val);FindPath(root->right,expectNumber-root->val);if(temp.size()>0)temp.pop_back();return result;}
};
复杂链表的复制
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
/*
struct RandomListNode {int label;struct RandomListNode *next, *random;RandomListNode(int x) :label(x), next(NULL), random(NULL) {}
};
*/
class Solution {
public:RandomListNode* Clone(RandomListNode* pHead){if(pHead==NULL)return NULL;RandomListNode* cur;cur = pHead;while(cur){RandomListNode* node = new RandomListNode(cur->label);node->next = cur->next;cur->next = node;cur = node->next;}//新链表和就链表链接:A->A'->B->B'->C->C'cur = pHead;RandomListNode* p;while(cur){p = cur->next;if(cur->random)p->random = cur->random->next; //关键cur = p->next;}RandomListNode* temp;RandomListNode* phead = pHead->next;cur = pHead;while(cur->next){temp = cur->next;cur->next = temp->next;cur = temp;}return phead;}
};
二叉搜索树与双向链表
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
/*
struct TreeNode {int val;struct TreeNode *left;struct TreeNode *right;TreeNode(int x) :val(x), left(NULL), right(NULL) {}
};*/
class Solution {
public:TreeNode* Convert(TreeNode* pRootOfTree){stack<TreeNode*> st;TreeNode *cur = pRootOfTree;TreeNode *pre = pRootOfTree;TreeNode *head = pRootOfTree;bool isFirst = true;while(cur||!st.empty()){while(cur){st.push(cur);cur = cur->left;}cur = st.top();st.pop();if(isFirst){head = pre = cur;isFirst = false;}else{pre->right = cur;cur->left = pre;pre = cur;}cur = cur->right;}return head;}
};
字符串的排列
输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
class Solution {
public:vector<string> result;vector<string> Permutation(string str) {if(str.length()==0)return result;permutation1(str,0);sort(result.begin(),result.end());return result;}void permutation1(string str,int begin){if(begin==str.length()){result.push_back(str);return;}for(int i = begin;str[i]!='\0';i++){if(i!=begin&&str[begin]==str[i])continue;swap(str[begin],str[i]);permutation1(str,begin+1);swap(str[begin],str[i]);}}
};
数组中出现次数超过一半的数字
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
class Solution {
public:int MoreThanHalfNum_Solution(vector<int> numbers) {int length = numbers.size();if (length==0)return 0;sort(numbers.begin(),numbers.end());int num = numbers[0];int max_count = 1;int count = 0;for(int i = 1;i<length;i++){if(numbers[i]!=numbers[i-1]){if(count>max_count){max_count = count;num = numbers[i-1];}count = 1;}else{count++;}}if(max_count>length/2){return num;}elsereturn 0;}
};
最小的K个数
输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。
class Solution {
public:vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {sort(input.begin(),input.end());vector<int> result;if(k>input.size())return result;for(int i = 0;i<k;i++){result.push_back(input[i]);}return result;}
};
连续子数组的最大和
HZ偶尔会拿些专业问题来忽悠那些非计算机专业的同学。今天测试组开完会后,他又发话了:在古老的一维模式识别中,常常需要计算连续子向量的最大和,当向量全为正数的时候,问题很好解决。但是,如果向量中包含负数,是否应该包含某个负数,并期望旁边的正数会弥补它呢?例如:{6,-3,-2,7,-15,1,2,2},连续子向量的最大和为8(从第0个开始,到第3个为止)。给一个数组,返回它的最大连续子序列的和,你会不会被他忽悠住?(子向量的长度至少是1)
class Solution {
public:int FindGreatestSumOfSubArray(vector<int> array) {int temp_max = array[0];int max_num = array[0];for(int i=1;i<array.size();i++){temp_max=max(array[i],array[i]+temp_max);max_num = max(temp_max,max_num);}return max_num;}
};
整数中1出现的次数
求出113的整数中1出现的次数,并算出1001300的整数中1出现的次数?为此他特别数了一下1~13中包含1的数字有1、10、11、12、13因此共出现6次,但是对于后面问题他就没辙了。ACMer希望你们帮帮他,并把问题更加普遍化,可以很快的求出任意非负整数区间中1出现的次数(从1 到 n 中1出现的次数)。
class Solution {
public:int NumberOf1Between1AndN_Solution(int n){int temp = n;int last;int result = 0;int base = 1;while(temp){last = temp%10;temp = temp/10;result += temp*base;if (last==1){result += n%base + 1;}else if(last>1){result += base;}base *=10;}return result;}
};
把数组排成最小的数
输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323
class Solution {
public:string PrintMinNumber(vector<int> numbers) {string res="";int length = numbers.size();if(length==0)return "";sort(numbers.begin(),numbers.end(),cmp);for(int i=0;i<length;i++)res += to_string(numbers[i]);return res;}static bool cmp(int a,int b){string A = to_string(a)+to_string(b);string B = to_string(b)+to_string(a);return A<B;}
};
丑数
把只包含质因子2、3和5的数称作丑数(Ugly Number)。例如6、8都是丑数,但14不是,因为它包含质因子7。 习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数
class Solution {
public:int GetUglyNumber_Solution(int index) {if(index<7)return index;int t2=0,t3=0,t5=0;vector<int> res(index);res[0]=1;for(int i = 1;i<index;i++){res[i] = min(res[t2]*2,min(res[t3]*3,res[t5]*5));if(res[i]==res[t2]*2)t2++;if(res[i]==res[t3]*3)t3++;if(res[i]==res[t5]*5)t5++;}return res[index-1];}
};
第一次只出现一次的字符
在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写)
class Solution {
public:int FirstNotRepeatingChar(string str) {int len = str.length();if(len==0)return -1;char ch[256] = {0};for(int i=0;i<len;i++)ch[str[i]]++;for(int i=0;i<len;i++){if(ch[str[i]]==1)return i;}return -1;}
};
数组中的逆序对
在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。 即输出P%1000000007
class Solution {
public:int InversePairs(vector<int> data) {long long res;vector<int> copy;for(auto num:data){copy.push_back(num);}res = inverseCount(data, 0, data.size()-1, copy);return res%1000000007;}long long inverseCount(vector<int>& temp,int begin,int end,vector<int>& data){if(end - begin==0){temp[end] = data[end];return 0;}if(end - begin==1){if(data[begin]<=data[end]){return 0;}else{temp[begin] = data[end];temp[end] = data[begin];return 1;}}int mid = (end+begin)/2;long long cnt = 0;long long left = inverseCount(data,begin,mid,temp);long long right = inverseCount(data,mid+1,end,temp);int i=begin;int j=mid+1;int index = begin;while(i<=mid && j<=end){if(data[i]<=data[j])//此时data是排序后的结果{temp[index] = data[i];i++;}else{temp[index] = data[j];j++;cnt = cnt + mid - i + 1;}index++;}while(i<=mid){temp[index] = data[i];i++;index++;}while(j<=end){temp[index] = data[j];j++;index++;}return cnt+left+right;}
};
两个链表的第一个公共结点
输入两个链表,找出它们的第一个公共结点。
/*
struct ListNode {int val;struct ListNode *next;ListNode(int x) :val(x), next(NULL) {}
};*/
class Solution {
public:ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {ListNode* p1 = pHead1;ListNode* p2 = pHead2;int len1=0,len2=0,diff;while(p1){len1++;p1 = p1->next;}while(p2){len2++;p2 = p2->next;}if(len1>len2){diff = len1 - len2;p1 = pHead1;p2 = pHead2;}else{diff = len2-len1;p1 = pHead2;p2 = pHead1;}for(int i=0;i<diff;i++){p1 = p1->next;}while(p1!=NULL && p2!=NULL){if(p1==p2)break;p1 = p1->next;p2 = p2->next;}return p1;}
};
数字在排序数组中出现的次数
统计一个数字在排序数组中出现的次数。
class Solution {
public:int GetNumberOfK(vector<int> data ,int k) {int count = 0;for(int i=0;i<data.size();i++){if(data[i]==k)count++;}return count;}
};
二叉树的深度
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度
/*
struct TreeNode {int val;struct TreeNode *left;struct TreeNode *right;TreeNode(int x) :val(x), left(NULL), right(NULL) {}
};*/
class Solution {
public:int TreeDepth(TreeNode* pRoot){if(!pRoot) return 0;return max(1+TreeDepth(pRoot->left),1+TreeDepth(pRoot->right));}
};
平衡二叉树
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
class Solution {
public:bool IsBalanced_Solution(TreeNode* pRoot) {if(pRoot==NULL)return true;int left_depth = getdepth(pRoot->left);int right_depth = getdepth(pRoot->right);if(left_depth>right_depth+1 || left_depth+1<right_depth)return false;elsereturn IsBalanced_Solution(pRoot->left) && IsBalanced_Solution(pRoot->right);}int getdepth(TreeNode* pRoot){if(pRoot==NULL)return 0;return max(1+getdepth(pRoot->left),1+getdepth(pRoot->right));}
};
数组中只出现一次的数字
一个整型数组里除了两个数字之外,其他的数字都出现了偶数次。请写程序找出这两个只出现一次的数字。
class Solution {
public:void FindNumsAppearOnce(vector<int> data,int* num1,int *num2) {int len = data.size();if(len<2)return;int one = 0;for(int i=0;i<len;i++){one = one^data[i];}int flag = 1;while(flag){if(one&flag)break;flag = flag<<1;}for(int i=0;i<len;i++){if(flag&data[i]) *num1 = *num1^data[i];else *num2 = *num2^data[i];}}
};
和为S的连续正数序列
小明很喜欢数学,有一天他在做数学作业时,要求计算出9~16的和,他马上就写出了正确答案是100。但是他并不满足于此,他在想究竟有多少种连续的正数序列的和为100(至少包括两个数)。没多久,他就得到另一组连续正数和为100的序列:18,19,20,21,22。现在把问题交给你,你能不能也很快的找出所有和为S的连续正数序列? Good Luck!
class Solution {
public:vector<vector<int> > FindContinuousSequence(int sum) {int m;vector<vector<int>> result;vector<int> num;for(int n = 1;n<sum;n++){m = 1;while(true){if((2*n+m)*(m+1)<2*sum)m = m+1;else if((2*n+m)*(m+1)==2*sum){for(int i = n;i<=n+m;i++){num.push_back(i);}result.push_back(num);num.clear();break;}elsebreak;}}return result;}
};
和为S的两个数字
输入一个递增排序的数组和一个数字S,在数组中查找两个数,使得他们的和正好是S,如果有多对数字的和等于S,输出两个数的乘积最小的。
class Solution {
public:vector<int> FindNumbersWithSum(vector<int> array,int sum) {vector<int> result;int len = array.size();if(len<=1)return result;int Sum;int i = 0;int j = len - 1;while(i<j){Sum = array[i] + array[j];if(Sum>sum) j--;else if(Sum<sum) i++;else{result.push_back(array[i]);result.push_back(array[j]);break;}}return result;}
};
左旋转字符串
汇编语言中有一种移位指令叫做循环左移(ROL),现在有个简单的任务,就是用字符串模拟这个指令的运算结果。对于一个给定的字符序列S,请你把其循环左移K位后的序列输出。例如,字符序列S=”abcXYZdef”,要求输出循环左移3位后的结果,即“XYZdefabc”。是不是很简单?OK,搞定它!
class Solution {
public:string LeftRotateString(string str, int n) {string str1;str1 = str.substr(0,n);str.erase(0,n);return str+str1;}
};
翻转单词顺序列
牛客最近来了一个新员工Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上。同事Cat对Fish写的内容颇感兴趣,有一天他向Fish借来翻看,但却读不懂它的意思。例如,“student. a am I”。后来才意识到,这家伙原来把句子单词的顺序翻转了,正确的句子应该是“I am a student.”。Cat对一一的翻转这些单词顺序可不在行,你能帮助他么?
class Solution {
public:string ReverseSentence(string str) {int len = str.size();int start = 0;for(int i = 0; i < len; i ++){if(str[i] == ' '){reverse(str.begin()+start, str.begin()+i);start = i+1;}if(i == len-1){reverse(str.begin()+start, str.end());}}reverse(str.begin(), str.end());return str;}
};
扑克牌顺子
LL今天心情特别好,因为他去买了一副扑克牌,发现里面居然有2个大王,2个小王(一副牌原本是54张_)…他随机从中抽出了5张牌,想测测自己的手气,看看能不能抽到顺子,如果抽到的话,他决定去买体育彩票,嘿嘿!!“红心A,黑桃3,小王,大王,方片5”,“Oh My God!”不是顺子…LL不高兴了,他想了想,决定大\小 王可以看成任何数字,并且A看作1,J为11,Q为12,K为13。上面的5张牌就可以变成“1,2,3,4,5”(大小王分别看作2和4),“So Lucky!”。LL决定去买体育彩票啦。 现在,要求你使用这幅牌模拟上面的过程,然后告诉我们LL的运气如何, 如果牌能组成顺子就输出true,否则就输出false。为了方便起见,你可以认为大小王是0。
class Solution {
public:bool IsContinuous( vector<int> numbers ) {if(numbers.empty())return 0;int len = numbers.size();int max = -1;int min = 14;int count[14]={0};for(int i=0;i<len;i++){count[numbers[i]]++;if(numbers[i]==0) continue;if(count[numbers[i]]>1) return 0;if(numbers[i]>max)max = numbers[i];if(numbers[i]<min)min = numbers[i];}if(max-min<5)return 1;return 0;}
};
孩子们的游戏(圆圈中最后剩下的数)
每年六一儿童节,牛客都会准备一些小礼物去看望孤儿院的小朋友,今年亦是如此。HF作为牛客的资深元老,自然也准备了一些小游戏。其中,有个游戏是这样的:首先,让小朋友们围成一个大圈。然后,他随机指定一个数m,让编号为0的小朋友开始报数。每次喊到m-1的那个小朋友要出列唱首歌,然后可以在礼品箱中任意的挑选礼物,并且不再回到圈中,从他的下一个小朋友开始,继续0…m-1报数…这样下去…直到剩下最后一个小朋友,可以不用表演,并且拿到牛客名贵的“名侦探柯南”典藏版(名额有限哦!!_)。请你试着想下,哪个小朋友会得到这份礼品呢?(注:小朋友的编号是从0到n-1)
class Solution {
public:int LastRemaining_Solution(int n, int m){//f(n,m)={f(n-1,m)+m}%n。if(n==0)return -1;int s=0;for(int i = 2;i<=n;i++){s =(s+m)%i;}return s;}
};
求1+2+3…+n
求1+2+3+…+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
class Solution {
public:int Sum_Solution(int n) {int res = n;res&&(res+=Sum_Solution(n-1));return res;}
};
不用加减乘除做加法
写一个函数,求两个整数之和,要求在函数体内不得使用+、-、*、/四则运算符号。
/*
首先看十进制是如何做的: 5+7=12,三步走
第一步:相加各位的值,不算进位,得到2。
第二步:计算进位值,得到10. 如果这一步的进位值为0,那么第一步得到的值就是最终结果。
第三步:重复上述两步,只是相加的值变成上述两步的得到的结果2和10,得到12。
同样我们可以用三步走的方式计算二进制值相加: 5-101,7-111 第一步:相加各位的值,不算进位,
得到010,二进制每位相加就相当于各位做异或操作,101^111。
第二步:计算进位值,得到1010,相当于各位做与操作得到101,再向左移一位得到1010,(101&111)<<1。
第三步重复上述两步, 各位相加 010^1010=1000,进位值为100=(010&1010)<<1。
继续重复上述两步:1000^100 = 1100,进位值为0,跳出循环,1100为最终结果 */
class Solution {
public:int Add(int num1, int num2){ return num2 ? Add(num1^num2, (num1&num2)<<1) : num1;}
};
把字符串转换成整数
将一个字符串转换成一个整数(实现Integer.valueOf(string)的功能,但是string不符合数字要求时返回0),要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0。
class Solution {
public:int StrToInt(string str) {int len = str.length();int s;int result;if(len<=0) result = 0;if(str[0]=='-')s = -1;elses = 1;for(int i = (str[i]=='-'||str[i]=='+')?1:0;i<len;++i){if(!(str[i]>='0' && str[i]<='9'))return 0;result = result*10+str[i]-'0';}return result*s;}
};
数组中重复的数字
在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。
class Solution {
public:// Parameters:// numbers: an array of integers// length: the length of array numbers// duplication: (Output) the duplicated number in the array number// Return value: true if the input is valid, and there are some duplications in the array number// otherwise falsebool duplicate(int numbers[], int length, int* duplication) {if(numbers==NULL || length ==0)return 0;int counttable[256] = {0};for(int i=0;i<length;i++){counttable[numbers[i]]++;}int count = 0;for(int i=0;i<length;i++){if(counttable[numbers[i]]>1){duplication[count++] = numbers[i];return true;}}return false;}
};
构建乘积数组
给定一个数组A[0,1,…,n-1],请构建一个数组B[0,1,…,n-1],其中B中的元素B[i]=A[0]A[1]…*A[i-1]A[i+1]…*A[n-1]。不能使用除法。
class Solution {
public:vector<int> multiply(const vector<int>& A) {vector<int> B;int length = A.size();for(int i=0;i<length;i++){int number=1;for(int j = 0;j<length;j++){if(j==i)continue;number *= A[j];}B.push_back(number);}return B;}
};
正则表达式匹配
请实现一个函数用来匹配包括’.‘和’‘的正则表达式。模式中的字符’.‘表示任意一个字符,而’'表示它前面的字符可以出现任意次(包含0次)。 在本题中,匹配是指字符串的所有字符匹配整个模式。例如,字符串"aaa"与模式"a.a"和"abaca"匹配,但是与"aa.a"和"ab*a"均不匹配。
class Solution {
public:bool match(char* str, char* pattern){if(str[0]=='\0' && pattern[0]=='\0')return true;if(str[0]!='\0' && pattern[0]=='\0')return false;if(pattern[1]=='*'){if(pattern[0]==str[0]||(pattern[0]=='.'&&str[0]!='\0'))return match(str+1,pattern) || match(str,pattern+2);elsereturn match(str,pattern+2);}if(str[0]==pattern[0]||(pattern[0]=='.'&& str[0]!='\0'))return match(str+1,pattern+1);return false;}
};
表示数值的字符串
请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串"+100",“5e2”,"-123",“3.1416"和”-1E-16"都表示数值。 但是"12e",“1a3.14”,“1.2.3”,"±5"和"12e+4.3"都不是。
//注意表示数值的字符串遵循的规则;
//在数值之前可能有一个“+”或“-”,接下来是0到9的数位表示数值的整数部分,如果数值是一个小数,那么小数点后面可能会有若干个0到9的数位
//表示数值的小数部分。如果用科学计数法表示,接下来是一个‘e’或者‘E’,以及紧跟着一个整数(可以有正负号)表示指数。
class Solution {
public:bool isNumeric(char* string){if(string==NULL or *string=='\0')return false;if(*string=='+'||*string=='-')string++;int dot=0,num=0,nume=0;while(*string != '\0'){if(*string>='0' && *string<='9'){string++;num =1;}else if(*string=='.'){if(dot>0||nume>0)return false;string++;dot = 1;}else if(*string=='e' || *string=='E'){if(nume>0||num==0)return false;string++;nume++;if(*string=='+' || *string=='-')string++;if(*string=='\0')return false;}elsereturn false;}return true;}
};
字符流中第一个不重复的字符
请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。
class Solution
{
public://Insert one char from stringstreamvoid Insert(char ch){s = s + ch;if(cha[ch])cha[ch]++;elsecha[ch] = 1;}//return the first appearence once char in current stringstreamchar FirstAppearingOnce(){int length = s.size();for(int i=0;i<length;i++){if(cha[s[i]]==1)return s[i];}return '#';}
private:char cha[256]={0};string s;
};
链表中环的入口结点
给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。
/*
struct ListNode {int val;struct ListNode *next;ListNode(int x) :val(x), next(NULL) {}
};
*/
class Solution {
public:ListNode* EntryNodeOfLoop(ListNode* pHead){if(pHead==NULL)return NULL;//找到环ListNode* pfast = pHead->next, *pslow = pHead;while(pfast!=NULL && pslow!=NULL && pslow!=pfast){pfast = pfast->next;pslow = pslow->next;if(pfast!=NULL)pfast = pfast->next;}//计算环的元素个数int count = 1;ListNode* temp = pfast->next;if(pfast==pslow&&pfast!=NULL){while(temp!=pfast){temp = temp->next;count++;}}elsereturn NULL;//找入口ListNode* phead1=pHead,*phead2=pHead;for(int i=0;i<count;i++)phead1 = phead1->next;while(phead1!=phead2){phead1 = phead1->next;phead2 = phead2->next;}return phead1;}
};
删除链表中重复的结点
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5。
/*
struct ListNode {int val;struct ListNode *next;ListNode(int x) :val(x), next(NULL) {}
};
*/
class Solution {
public:ListNode* deleteDuplication(ListNode* pHead){ListNode* result = new ListNode(0);ListNode* res = result;result->next = pHead;ListNode* temp = pHead;while(temp && temp->next){if(temp->val==temp->next->val){while(temp->next && temp->val==temp->next->val){temp = temp->next;}}else{res->next = temp;res = res->next;}temp = temp->next;}res->next = temp;return result->next;}
};
二叉树的下一个结点
给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。
/*
struct TreeLinkNode {int val;struct TreeLinkNode *left;struct TreeLinkNode *right;struct TreeLinkNode *next;TreeLinkNode(int x) :val(x), left(NULL), right(NULL), next(NULL) {}
};
*/
/*分析二叉树的下一个节点,一共有以下情况:
1.二叉树为空,则返回空;
2.节点右孩子存在,则设置一个指针从该节点的右孩子出发,一直沿着指向左子结点的指针找到的叶子节点即为下一个节点;
3.节点不是根节点。如果该节点是其父节点的左孩子,则返回父节点;否则继续向上遍历其父节点的父节点,重复之前的判断,返回结果*/
class Solution {
public:TreeLinkNode* GetNext(TreeLinkNode* pNode){if(pNode==NULL)return NULL;if(pNode->right!=NULL){pNode = pNode->right;while(pNode->left){pNode = pNode->left;}return pNode;}while(pNode->next!=NULL){TreeLinkNode* proot = pNode->next;if(proot->left == pNode)return proot;pNode=pNode->next;}return NULL;}
};
对称二叉树
请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
/*
struct TreeNode {int val;struct TreeNode *left;struct TreeNode *right;TreeNode(int x) :val(x), left(NULL), right(NULL) {}
};
*/
class Solution {
public:bool isSymmetrical(TreeNode* pRoot){return issymmetrical(pRoot,pRoot);}bool issymmetrical(TreeNode* pRoot1,TreeNode* pRoot2){if(pRoot1==NULL && pRoot2==NULL)return true;if(pRoot1==NULL || pRoot2==NULL)return false;if(pRoot1->val!=pRoot2->val)return false;return issymmetrical(pRoot1->right,pRoot2->left) && issymmetrical(pRoot1->left,pRoot2->right);}};
按之字形顺序打印二叉树
请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
/*
struct TreeNode {int val;struct TreeNode *left;struct TreeNode *right;TreeNode(int x) :val(x), left(NULL), right(NULL) {}
};
*/
class Solution {
public:vector<vector<int> > Print(TreeNode* pRoot) {vector<vector<int>> result;if(pRoot==nullptr)return result;stack<TreeNode*> stack1,stack2;//分别存奇数和偶数层stack1.push(pRoot);while(!stack1.empty() || !stack2.empty()){if(!stack1.empty()){vector<int> temp;while(!stack1.empty()){TreeNode *data=stack1.top();stack1.pop();temp.push_back(data->val);if(data->left!=nullptr)stack2.push(data->left);if(data->right!=nullptr)stack2.push(data->right);}result.push_back(temp);}if(!stack2.empty()){vector<int> temp;while(!stack2.empty()){TreeNode *data=stack2.top();stack2.pop();temp.push_back(data->val);if(data->right!=nullptr)stack1.push(data->right);if(data->left!=nullptr)stack1.push(data->left);}result.push_back(temp);}}return result;}
};
把二叉树打印成多行
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
/*
struct TreeNode {int val;struct TreeNode *left;struct TreeNode *right;TreeNode(int x) :val(x), left(NULL), right(NULL) {}
};
*/
class Solution {
public:vector<vector<int> > Print(TreeNode* pRoot) {vector<vector<int> > ans;if(pRoot == NULL) return ans;queue<TreeNode*> q;q.push(pRoot);while(!q.empty()){int size = q.size();//读取每一层的元素的数量vector<int> levelelem;while(size--){TreeNode* t = q.front();q.pop();levelelem.push_back(t->val);if(t->left != NULL) q.push(t->left);if(t->right != NULL) q.push(t->right);}ans.push_back(levelelem);}return ans;}
};
序列化二叉树
请实现两个函数,分别用来序列化和反序列化二叉树
/*
struct TreeNode {int val;struct TreeNode *left;struct TreeNode *right;TreeNode(int x) :val(x), left(NULL), right(NULL) {}
};
*/
class Solution {
public:vector<int> buf;void dfs1(TreeNode *root) {if(!root) buf.push_back(0xFFFFFFFF);else {buf.push_back(root->val);dfs1(root->left);dfs1(root->right);}}TreeNode* dfs2(int* &p) {if(*p==0xFFFFFFFF) {p++;return NULL;}TreeNode* res=new TreeNode(*p);p++;res->left=dfs2(p);res->right=dfs2(p);return res;}char* Serialize(TreeNode *root) {buf.clear();dfs1(root);int bufSize=buf.size();int *res=new int[bufSize];for(int i=0;i<bufSize;i++) res[i]=buf[i];return (char*)res;}TreeNode* Deserialize(char *str) {int *p=(int*)str;return dfs2(p);}
};
二叉搜索树的第k个结点
给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。
//思路:二叉搜索树按照中序遍历的顺序打印出来正好就是排序好的顺序。
// 所以,按照中序遍历顺序找到第k个结点就是结果。
/*
struct TreeNode {int val;struct TreeNode *left;struct TreeNode *right;TreeNode(int x) :val(x), left(NULL), right(NULL) {}
};
*/
class Solution {int count = 0;
public:TreeNode* KthNode(TreeNode* pRoot, unsigned int k){if(pRoot){ TreeNode *ret = KthNode(pRoot->left, k);if(ret) return ret;if(++count == k) return pRoot;ret = KthNode(pRoot->right,k);if(ret) return ret;}return nullptr;}
};
数据流中的中位数
如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。我们使用Insert()方法读取数据流,使用GetMedian()方法获取当前读取数据的中位数
class Solution {vector<double> data;
public:void Insert(int num){data.push_back(num);sort(data.begin(),data.end());}double GetMedian(){int length = data.size();if(length%2==0){return (data[length/2]+data[length/2-1])/2;}else{return data[(length/2)];}}
};
滑动窗口的最大值
给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。例如,如果输入数组{2,3,4,2,6,2,5,1}及滑动窗口的大小3,那么一共存在6个滑动窗口,他们的最大值分别为{4,4,6,6,6,5}; 针对数组{2,3,4,2,6,2,5,1}的滑动窗口有以下6个: {[2,3,4],2,6,2,5,1}, {2,[3,4,2],6,2,5,1}, {2,3,[4,2,6],2,5,1}, {2,3,4,[2,6,2],5,1}, {2,3,4,2,[6,2,5],1}, {2,3,4,2,6,[2,5,1]}。
class Solution {
public:vector<int> maxInWindows(const vector<int>& num, unsigned int size){int count = num.size()-size+1;vector<int> result;if(size==0 || num.size()==0){return result;}for(int i =0;i<count;i++){int max_number = *max_element(num.begin()+i,num.begin()+size+i);result.push_back(max_number);}return result;}
};
矩阵中的路径
请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则之后不能再次进入这个格子。 例如 a b c e s f c s a d e e 这样的3 X 4 矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。
class Solution {
private:bool isPath(char *matrix,vector<char> flags,char* str,int x,int y,int rows, int cols){if(x<0 || x>=rows || y<0 || y>=cols) //越界的点return false; if( matrix[x*cols+y]== *str && flags[x*cols+y]==0 ){flags[x*cols+y]=1;if(*(str+1)==0) // 字符串结尾了(最后一个满足的)return true;bool condition =isPath(matrix,flags,(str+1),x,y-1,rows,cols) ||isPath(matrix,flags,(str+1),x-1,y,rows,cols)||isPath(matrix,flags,(str+1),x,y+1,rows,cols)||isPath(matrix,flags,(str+1),x+1,y,rows,cols); if(condition == false)flags[x*cols+y]=0;return condition; } elsereturn false;}public:bool hasPath(char* matrix, int rows, int cols, char* str){vector<char> flags(rows*cols,0);bool condition=false;for(int i=0;i<rows;i++)for(int j=0;j<cols;j++){condition= (condition || isPath(matrix,flags,str,i,j,rows,cols) );}return condition; }
};
机器人的运动范围
地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
class Solution {
public:int movingCount(int threshold, int rows, int cols) {vector<vector<int>> flag(rows+1); //记录是否已经走过for(int i=0;i<rows+1;++i){flag[i].resize(cols+1,0);}return helper(0, 0, rows, cols, flag, threshold);}private:int helper(int i, int j, int rows, int cols, vector<vector<int>>& flag, int threshold) {if (i < 0 || i >= rows || j < 0 || j >= cols || numSum(i) + numSum(j) > threshold || flag[i][j] == 1)return 0; flag[i][j] = 1;return helper(i - 1, j, rows, cols, flag, threshold)+ helper(i + 1, j, rows, cols, flag, threshold)+ helper(i, j - 1, rows, cols, flag, threshold)+ helper(i, j + 1, rows, cols, flag, threshold)+ 1;}int numSum(int i) {int sum = 0;do{sum += i%10;}while((i = i/10) > 0);return sum;}
};
剑指offer(C++版本)相关推荐
- 剑指offer最新版_剑指Offer——Java版本(持续更新)
0 前言 邻近校招,算法要命!!! 本文为研究剑指Offer过程中的笔记,整理出主要思路以及Java版本题解,以便记忆和复习. 参考整理来自<剑指Offer 第二版>. 特别注意,对每道题 ...
- 三天刷完《剑指OFFER编程题》--Java版本实现(第三天)
正在更新中......... 剑指offer --Python版本的实现: 剑指offer(1/3)第一大部分 剑指offer(2/3)第二大部分 剑指offer(3/3)第三大部分 -------- ...
- java牛客排序算法题_《剑指offer》面试题28:字符串的排列(牛客网版本) java...
输入一个字符串,按字典序打印出该字符串中字符的所有排列.例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba. 输入描述: 输入一个字符 ...
- JavaScript-牛客网-剑指offer(1-10)题解
牛客网-剑指Offer题解-js版本 剑指offer第1-10题解答(js) 1.二维数组中查找 2.替换空格 3.从尾到头打印链表 4.重建二叉树 5.用两个栈实现一个队列 6.旋转数组中的最小数字 ...
- JavaScript-牛客网-剑指offer(41-50)题解
牛客网剑指Offer题解javascript版本 剑指offer第41-50题解答(javascript) 41.和为S的连续正数序列 42.和为S的两个数字 43.左旋转字符串 44.翻转单词顺序列 ...
- 《剑指Offer》 二维数组的查找 C语言版本
文章目录 前言 题目解析 图片演示 target = 7 1.从矩阵左下角元素开始遍历,将其与目标值进行对比 2.元素18大于目标值7,行`row`索引向上移动一格 3.元素10大于目标值7,行`ro ...
- 剑指offer(Python版本)--精心整理
剑指offer(Python版本) 1.二维数组的查找 2.替换空格 3.从尾到头打印链表 4.重建二叉树 5.用两个栈实现队列 6.旋转数组的最小数字 7.斐波那契数列 8.跳台阶 9.变态跳台阶 ...
- 《剑指offer》c++版本 14.剪绳子
本题在牛客网剑指offer专项里没看到,原书第二版上有,如题: 这道题是开放的动态规划题,题目中只给了绳子长度,却没定义具体剪多少段,初遇此题,难以下手,看了题解,豁然开朗.设f(n)为常为n的绳子剪 ...
- 《剑指offer》c++版本 12. 矩阵中的路径
如题,牛客网上题目没有图示,下图是从原书中截图得到的. 本题就是从数组中按照指定方向查找字符序列,典型的回溯行为,找到当前字符,继续查找该字符上下左右四个方向,找不到,返回上一个字符,重新查找.题目要 ...
- 【leetcode】 剑指 Offer学习计划(java版本含注释)(上)
目录 前言 第一天(栈与队列) 剑指 Offer 09. 用两个栈实现队列(简单) 剑指 Offer 30. 包含min函数的栈(简单) 第二天(链表) 剑指 Offer 06. 从尾到头打印链表(简 ...
最新文章
- 云服务商正在杀死开源商业模式
- 【GDAL】聊聊GDAL的数据模型(二)——Band对象
- Linux内核裁剪及编译
- python当用户输入的不是整数_当用户输入字符串而不是整数时,如何保护我的python代码?...
- 如何部署一个Kubernetes集群
- arp协议、arp应答出现的原因、arp应答过程、豁免ARP详细解答附图(建议电脑观看)
- AWR6843芯片使用JFlash下载外部NorFlash
- 交换机接出来的网线可以再接上无线路由器实现无线上网吗
- “如果Java受到一两个大型供应商的控制,则可能会遭受挫折”
- 支持服务器CPU的ITX主板,广积科技发布支持英特尔Xeon E处理器的Mini-ITX主板--MI995...
- 为什么高级程序员不必担心自己的技术过时?
- 如何用jira做管理?
- 可燃气体传感器在智慧消防中的应用
- This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the foll
- Istio 流量管理 virtualservice (1)
- 又拍网刘平阳:广告为图片网站主要盈利模式
- python表达式3**2**3的值为_Python表达式 1/2 的值为 , 1//3+1//3+1//3 的值为 ,5%3的值为 。_会计基础与实务答案_学小易找答案...
- 【Android工具】免费好用无广告安卓手机解压缩软件工具:ZArchiver
- [AI画图本地免安装部署]Windows 10 Nvidia平台部署AUTOMATIC1111 版本 stable diffusion 免安装版
- MBA-day5 逻辑学-假言推理考点
热门文章
- php dht爬虫,利用DHT网络,爬取bt种子。
- 设置Log4j配置文件路径
- Java api监控_网站api监控、api监控教程详解
- uefi模式下修改Intel网卡MAC地址
- ddwrt php,DD-WRT官方支持设备列表_ddwrt
- STM8L驱动I2C类型的12864
- ie剪切增强版工具---自由填表工具filltable
- 【620】【信息管理学基础】【真题背诵】
- 扫描仪标准模板滑动采集图像及其处理
- Real Estate Photography: Exterior at Twilight 房地产摄影:暮光之城 Lynda课程中文字幕