LeetCode之Counting Bits

本文探讨了利用二叉树结构解决计算整数比特数的问题,并详细阐述了算法实现过程,包括时间复杂度分析。
class Solution {
public:
	vector<int> countBits(int num) {
		if (num == 0){
			data.push_back(0);
			return data;
		}
		int level = ceil(log2(num+1));
		int count1 = 0; //目前栈中1的个数
		int count2 = 0; //目前栈中元素的个数
		int	count3 = 0; //输出结点的个数
		int temp;
		while (1){
			while (count2 < level-1){
				sta.push(0);
				count2++;
			}
			if (count2==level-1){//只有到叶子结点的上一层时才输出
				data.push_back(count1); //0入栈
				count3++;
				if (count3 == num + 1)break;
				data.push_back(count1 + 1); //1入栈
				count3++;
				if (count3 == num + 1)break;
			}
			temp = sta.top();
			while (count2>0&&temp==1){
				if (count3 == num + 1){
					cout <<"finished!"<< endl;
				}
				sta.pop();
				count2--;
				count1--;
				if(count2>0)temp = sta.top();
			}
			if (count2>0&&temp==0){
				sta.pop();
				sta.push(1);
				count1++;
			}
		}
		return data;
	}
	stack<int>sta;
	vector<int>data;
};

/*算法综述:

在这个算法中我们利用如下的树型结构:

                                          start
                                        /       \
                                       /         \
                                      0           1  
                                    /   \        / \
                                   0     1      0   1  
                                  / \   / \    /\   /\
                                 0   1 0   1  0  1 0  1  

                      对应的数   0   1 2   3  4  5 6  7

所以利用二叉树的遍历方法就可以求解法。
算法的时间复杂度为O(NlogN)
ps:leetcode上的运行时间为144ms,有点长,算法待改进!
*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值