题目
5.用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
class Solution//栈实现队列
{
public:
void push(int node) {
stack1.push(node);
}
int pop() {
if (stack2.empty())
{
while (!stack1.empty())
{
int tmp = stack1.top();
stack1.pop();
stack2.push(tmp);
}
class Solution//栈实现队列
{
public:
void push(int node) {
stack1.push(node);
}
int pop() {
if (stack2.empty())
{
while (!stack1.empty())
{
int tmp = stack1.top();
stack1.pop();
stack2.push(tmp);
}
if (stack2.empty())
{
return -1;
}
}
int root = stack2.top();
stack2.pop();
return root;
}
private:
stack<int> stack1;
stack<int> stack2;
};
}
int root = stack2.top();
stack2.pop();
return root;
}
private:
stack<int> stack1;
stack<int> stack2;
};
6.把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。 输入一个非减排序的数组的一个旋转,输出旋转数组的最小元素。 例如数组{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;
}
int min = rotateArray[0];
for (int i = 1; i < rotateArray.size(); i++)
{
if (rotateArray[i] < min)
min = rotateArray[i];
}
return min;
}
};
7.斐波那契数列/跳台阶
class Solution {//斐波那契
public:
int Fibonacci(int n) {
int a = 1;
int b = 1;
int value = 0;
if (n == 0){
return 0;
}
else if (n == 1|n == 2){
return 1;
}
else
{
for (int i = 0; i < n-2; i++)
{
value = a + b;
a = b;
b = value;
}
return b;
}
}
};
8.我们可以用2*1的小矩形横着或者竖着去覆盖更大的矩形。请问用n个2*1的小矩形无重叠地覆盖一个2*n的大矩形,总共有多少种方法?
class Solution {
public:
int rectCover(int n) {
if (n==1|n==0|n==2)
{
return n;
}
return rectCover(n-1)+rectCover(n-2);
}
};
9.输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。
class Solution {
public:
int NumberOf1(int n) {
int count=0;
while (n)
{
n = n&(n - 1);
count++;
}
return count;
}
};
10.给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方
class Solution {
public:
double Power(double base, int exponent) {
double value = 1;
int n=exponent;
if (n == 0)
{
return 1;
}
else if(n>0)
{
while (n)
{
value *= base;
n--;
}
return value;
}
else
{
while(-n)
{
value *= base;
n++;
}
return 1.0/value;
}
}
};