题目:
Given an array of integers, every element appears three times except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
代码:
class Solution { public: int singleNumber(vector<int>& nums) { int result = 0; const int W = sizeof(int)*8; int *count = new int[W](); for (size_t i = 0; i < nums.size(); ++i) { for (size_t j = 0; j < W; ++j) { count[j] += (nums[i] >> j) & 1; } } for (size_t i = 0; i < W; ++i) { if ( count[i]%3!=0 ) { result += ( 1 << i); } } delete []count; return result; } };
Tips:
1. 算法原理:由于都是int型的,只需要记录每个bit上1出现的次数;如果1出现的次数不是3的倍数,则将该位置置为1,并赋值到result中。
这道题主要是熟悉下位运算的各种操作,有时巧用位运算,可以大大提升代码效率。
时间: 2024-11-05 13:29:05