【LeetCode】24.Single Number II

博客围绕LeetCode上一道中等难度题目展开,题目要求在非空整数数组中,找出除一个元素只出现一次外,其余元素都出现三次的那个数,需线性时间复杂度且不使用额外内存。给出了示例,还进行算法分析,介绍通过创建数组统计每位1的次数来求解。

题目描述(Medium)

Given a non-empty array of integers, every element appears three times except for one, which appears exactly once. Find that single one.

Note:

Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

题目链接

https://leetcode.com/problems/single-number-ii/description/

Example 1:

Input: [2,2,3,2]
Output: 3

Example 2:

Input: [0,1,0,1,0,1,99]
Output: 99

算法分析

创建一个长度为sizeof(int)的数组count[sizeof(int)],count[i]表示在i位出现的1的次数。如果count[i]是3的整数倍,则忽略;否则就把该位取出来组成答案,时间复杂度为O(n),空间复杂度O(1)

提交代码:

class Solution {
public:
	int singleNumber(vector<int>& nums) {
		const int W = 8 * sizeof(int);
		int count[W];
		fill_n(count, W, 0);

		for (int i = 0; i < nums.size(); ++i)
		{
			for (int j = 0; j < W; ++j)
			{
				count[j] += (nums[i] >> j) & 0x1;
				count[j] %= 3;
			}
		}

		int result = 0;
		for (int i = 0; i < W; ++i)
			result += (count[i] << i);

		return result;
	}
};

测试代码:

// ====================测试代码====================
void Test(const char* testName, vector<int>& nums, int expected)
{
	if (testName != nullptr)
		printf("%s begins: \n", testName);

	Solution s;
	int result = s.singleNumber(nums);

	if (result == expected)
		printf("passed\n");
	else
		printf("failed\n");

}

int main(int argc, char* argv[])
{
	vector<int> ratings = { 2, 2, 3, 2 };
	Test("Test1", ratings, 3);

	ratings = { 0, 1, 0, 1, 0, 1, 99 };
	Test("Test2", ratings, 99);
	
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值