在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
class Solution {
public:
bool Find(int target, vector > array) {
int row = array.size();
int col = array[0].size();
for(int i=0;i|
请实现一个函数,将一个字符串中的每个空格替换成“%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 printListFromTailToHead(ListNode* head) {
ListNode* p=head;
vector 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 pre,vector vin) {
int len=vin.size();
if (len==0)
return NULL;
vector left_pre,right_pre,left_vin,right_vin;
TreeNode* head = new TreeNode(pre[0]);
int gen = 0;
for(int i=0;ileft = 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 rotateArray) {
/*if(rotateArray.size()== 0)
{
return 0;
}
else{
int i = 0;
while(rotateArray[i]> rotateArray[i+1])
{
i++;
}
vector resultArray;
int m = 0;
for(int j=i+1;j
大家都知道斐波那契数列,现在要求输入一个整数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的个数。其中负数用补码表示。
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 &array) {
vector result_even, result_odd;
for(int i=0;i
输入一个链表,输出该链表中倒数第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;
else
p = 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 printMatrix(vector > matrix) {
int cir = 0;
int row = matrix.size();
int col = matrix[0].size();
vector ans;
while(row>2*cir && col>2*cir){
//上面
for(int i=cir;i<=col-cir-1;i++)
ans.push_back(matrix[cir][i]);
//右面
if(circir && row-1-cir>cir){
for(int i=col-cir-2;i>=cir;i--)
ans.push_back(matrix[row-1-cir][i]);
}
//左面
if(cir=cir+1;i--)
ans.push_back(matrix[i][cir]);
}
cir++;
}
return ans;
}
};
定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
class Solution {
public:
void push(int value) {
stack1.push(value);
if(stackmin.empty())
stackmin.push(value);
else if (stackmin.top() stack1;
stack stackmin;
};
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)
class Solution {
public:
bool IsPopOrder(vector pushV,vector popV) {
stack st;
for(int i=0;i
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
vector PrintFromTopToBottom(TreeNode* root) {
vector result;
queue 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 sequence) {
if(sequence.empty())
return false;
int index;
int begin = 0;
int end = sequence.size()-1;
int root = sequence[end];
for(index = begin;indexroot)
break;
for(int j = index;index left_sq(sequence.begin(),sequence.begin()+index);
if(index>begin)
left = VerifySquenceOfBST(left_sq);
bool right = true;
vector right_sq(sequence.begin()+index+1,sequence.end());
if(index
输入一颗二叉树的跟节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
vector> result;
vector temp;
vector > 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 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 result;
vector 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 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;imax_count)
{
max_count = count;
num = numbers[i-1];
}
count = 1;
}
else
{
count++;
}
}
if(max_count>length/2){
return num;
}
else
return 0;
}
};
输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。
class Solution {
public:
vector GetLeastNumbers_Solution(vector input, int k) {
sort(input.begin(),input.end());
vector result;
if(k>input.size())
return result;
for(int i = 0;i
HZ偶尔会拿些专业问题来忽悠那些非计算机专业的同学。今天测试组开完会后,他又发话了:在古老的一维模式识别中,常常需要计算连续子向量的最大和,当向量全为正数的时候,问题很好解决。但是,如果向量中包含负数,是否应该包含某个负数,并期望旁边的正数会弥补它呢?例如:{6,-3,-2,7,-15,1,2,2},连续子向量的最大和为8(从第0个开始,到第3个为止)。给一个数组,返回它的最大连续子序列的和,你会不会被他忽悠住?(子向量的长度至少是1)
class Solution {
public:
int FindGreatestSumOfSubArray(vector array) {
int temp_max = array[0];
int max_num = array[0];
for(int i=1;i
求出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 numbers) {
string res="";
int length = numbers.size();
if(length==0)
return "";
sort(numbers.begin(),numbers.end(),cmp);
for(int i=0;i
把只包含质因子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 res(index);
res[0]=1;
for(int i = 1;i
在一个字符串(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
在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。 即输出P%1000000007
class Solution {
public:
int InversePairs(vector data) {
long long res;
vector copy;
for(auto num:data){
copy.push_back(num);
}
res = inverseCount(data, 0, data.size()-1, copy);
return res%1000000007;
}
long long inverseCount(vector& temp,int begin,int end,vector& 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;inext;
}
while(p1!=NULL && p2!=NULL){
if(p1==p2)
break;
p1 = p1->next;
p2 = p2->next;
}
return p1;
}
};
统计一个数字在排序数组中出现的次数。
class Solution {
public:
int GetNumberOfK(vector data ,int k) {
int count = 0;
for(int i=0;i
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度
/*
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+1left) && 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 data,int* num1,int *num2) {
int len = data.size();
if(len<2)return;
int one = 0;
for(int i=0;i
小明很喜欢数学,有一天他在做数学作业时,要求计算出9~16的和,他马上就写出了正确答案是100。但是他并不满足于此,他在想究竟有多少种连续的正数序列的和为100(至少包括两个数)。没多久,他就得到另一组连续正数和为100的序列:18,19,20,21,22。现在把问题交给你,你能不能也很快的找出所有和为S的连续正数序列? Good Luck!
class Solution {
public:
vector > FindContinuousSequence(int sum) {
int m;
vector> result;
vector num;
for(int n = 1;n
输入一个递增排序的数组和一个数字S,在数组中查找两个数,使得他们的和正好是S,如果有多对数字的和等于S,输出两个数的乘积最小的。
class Solution {
public:
vector FindNumbersWithSum(vector array,int sum) {
vector result;
int len = array.size();
if(len<=1)return result;
int Sum;
int i = 0;
int j = len - 1;
while(isum) j--;
else if(Sum
汇编语言中有一种移位指令叫做循环左移(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 numbers ) {
if(numbers.empty())return 0;
int len = numbers.size();
int max = -1;
int min = 14;
int count[14]={0};
for(int i=0;i1) return 0;
if(numbers[i]>max)max = numbers[i];
if(numbers[i]
每年六一儿童节,牛客都会准备一些小礼物去看望孤儿院的小朋友,今年亦是如此。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,要求不能使用乘除法、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;
else
s = 1;
for(int i = (str[i]=='-'||str[i]=='+')?1:0;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 false
bool duplicate(int numbers[], int length, int* duplication) {
if(numbers==NULL || length ==0)return 0;
int counttable[256] = {0};
for(int i=0;i1){
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 multiply(const vector& A) {
vector B;
int length = A.size();
for(int i=0;i
请实现一个函数用来匹配包括’.‘和’‘的正则表达式。模式中的字符’.‘表示任意一个字符,而’'表示它前面的字符可以出现任意次(包含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);
else
return 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;
}
else
return false;
}
return true;
}
};
请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。
class Solution
{
public:
//Insert one char from stringstream
void Insert(char ch)
{
s = s + ch;
if(cha[ch])
cha[ch]++;
else
cha[ch] = 1;
}
//return the first appearence once char in current stringstream
char FirstAppearingOnce()
{
int length = s.size();
for(int i=0;i
给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出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++;
}
}
else
return NULL;
//找入口
ListNode* phead1=pHead,*phead2=pHead;
for(int i=0;inext;
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 > Print(TreeNode* pRoot) {
vector> result;
if(pRoot==nullptr)
return result;
stack stack1,stack2;//分别存奇数和偶数层
stack1.push(pRoot);
while(!stack1.empty() || !stack2.empty()){
if(!stack1.empty()){
vector 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 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 > Print(TreeNode* pRoot) {
vector > ans;
if(pRoot == NULL) return ans;
queue q;
q.push(pRoot);
while(!q.empty()){
int size = q.size();//读取每一层的元素的数量
vector 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 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
给定一棵二叉搜索树,请找出其中的第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 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 maxInWindows(const vector& num, unsigned int size)
{
int count = num.size()-size+1;
vector result;
if(size==0 || num.size()==0){
return result;
}
for(int i =0;i
请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则之后不能再次进入这个格子。 例如 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 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;
}
else
return false;
}
public:
bool hasPath(char* matrix, int rows, int cols, char* str)
{
vector flags(rows*cols,0);
bool condition=false;
for(int i=0;i
地上有一个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> flag(rows+1); //记录是否已经走过
for(int i=0;i>& 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;
}
};