剑指offer C++ 2.4算法和数据操作题解

旋转数组的最小值

class Solution {
public:
	//基于二分查找算法的快速解法
	int minNumberInRotateArray(vector<int> rotateArray) {
		if (rotateArray.empty())
			return 0;
		else
		{
			int index1 = 0;
			int index2 = rotateArray.size() - 1;
			int indexMid = index1; //当把数组前面0个元素搬到后面时,即排序数组本身,第一个数字就是最小数字,可以直接返回
			while (rotateArray[index1] > rotateArray[index2])
			{
				if (index2 - index1 == 1)
				{
					return rotateArray[index2];
					break;
				}
				//二分查找
				indexMid = (index1 + index2) / 2;
				if (rotateArray[indexMid] >= rotateArray[index1])
					index1 = indexMid;
				if (rotateArray[indexMid] <= rotateArray[index2])
					index2 = indexMid;
 
				//当index1、index2和indexMid位置的值相等时,无法判断indexMid属于前半部分还是后半部分,需要遍历查找
				if (rotateArray[index1] == rotateArray[index2] && rotateArray[index1] == rotateArray[indexMid])
					return minInorder(rotateArray, index1, index2);
			}
			return rotateArray[indexMid];
		}
	}
 
	/*实现顺序查找*/
	int minInorder(vector<int> Array, int index1, int index2)
	{
		int result = Array[index1];
		for (int i = index1+1;i <= index2;i++)
		{
			if (Array[i] < result)
				result = Array[i];
		}
		return result;
	}
};

斐波那契数列
1、1、2、3、5、8、13、21、34

class Solution {
public:
	int Fibonacci(int n)
	{
		if (n == 0)
			return 0;
		if (n == 1)
			return 1;
		long long Fibonaccione = 0;
		long long Fibonaccitwo = 1;
		long long FibonacciN = 0;
		for (int i = 2;i <= n;i++)
		{
			FibonacciN = Fibonaccione + Fibonaccitwo;
			Fibonaccione = Fibonaccitwo;
			Fibonaccitwo = FibonacciN;
		}
		return FibonacciN;
	}
};

青蛙跳台阶

一次跳一阶或两阶:总共有多少种跳法:f(n)=f(n-1)+f(n-2)

变态跳台阶
一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。

思路:
记n级台阶的跳法总数目为f(n)
当n=1时:f(1)=1
当n=2时:f(2)=2
当n=3时:f(3)=4
当n=4时:f(4)=8

由归纳总结法得知:f(n)=2^(n-1)

class Solution {
public:
	int jumpFloor(int number) {
		if (number == 0)
			return 0;
		else if (number == 1)
			return 1;
		else
		{
			long long FloorIIN = 1;
			for (int i = 2; i <= number;i++)
				FloorIIN = FloorIIN * 2;
			return FloorIIN;
		}
	}
};

位运算
二进制中1的个数

/*利用移位运算来求解,不会引起死循环,但是循环次数多*/
	int NumberOf1(int n)
	{
		unsigned flag = 1;
		int count = 0;
		while (flag) // 这个循环次数等于整数二进制的位数,32位的整数要循环32次
		{
			if (n&flag)//如n的第某位为1,则结果为1;如某位为0,则结果为0
				count++;
			flag = flag << 1;
		}
		return count;
	}
//!!!! n位数为几,就循环几次	

把一个整数减去l,再和原整数做与运算,会把该整数最右边一个1变成0。
那么一个整数的二进制表示中有多少个1,就可以进行多少次这样的操作。
基于这种思路,我们可以写出新的代码:

/*利用位移运算来求解3,不会引起死循环,而且循环次数少,有几个1就循环几次*/
	int NumberOf1(int n)
	{
		int count = 0;
		while (n)
		{
			count++;
			n = (n - 1)&n;
		}
		return count;
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值