码迷,mamicode.com
首页 > 其他好文 > 详细

Single Number II

时间:2014-09-02 17:46:55      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:leetcode

Given an array of integers, every element appears three times except for one. Find that single one.

#include<iostream>
#include<unordered_map>
#include<vector>
using namespace std;
#define STOP system("pause")
#if 0
class Solution {
public:
	int singleNumber(int A[], int n) {
		unordered_map<int ,int> hash_map;
		for (int i = 0; i < n; i++){
			++hash_map[A[i]];
			if (hash_map[A[i]] == 3) hash_map.erase(A[i]);
		}
		return hash_map.begin()->first;
	}
};
#elif 1
class Solution {
public :
	int singleNumber(int A[], int n){
		vector<int> bit_num(32, 0);
		for (int i = 0; i < n; i++){
			for (int j = 0; j < 32; j++){
				if (A[i] & 1 << j)
					bit_num[j]++;
			}
		}
		int res = 0;
		for (int i = 0; i < 32; i++)
			res += (bit_num[i] % 3) << i;
		return res;
	}
};
#endif 
void test0(){
	int A[] = { 1, 2, 3, 1, 2, 3, 1, 2, 3, 6 };
	Solution ss;
	int res = ss.singleNumber(A,10);
	if (res != 6)
		printf("error");
	else
		printf("passed");
}
int main(){
	test0();
	STOP;
	return 0;
}

Single Number II

标签:leetcode

原文地址:http://blog.csdn.net/u011409995/article/details/39009059

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!