您的位置:首页 > 其它

[LeetCode] Single Number II

2013-10-19 23:25 309 查看
Given an array of integers, every element appears three[/i] times except for one. Find that single one.

Note:[/b]
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

class Solution {
public:
int singleNumber(int A[], int n) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if(n < 1 || n %3 != 1)
return -1;
map<int, int> mp;
map<int, int> ::iterator it;
for(int i = 0; i < n; i++) {
it = mp.find(A[i]);
if(it == mp.end())
mp[A[i]] = 1;
else
mp[A[i]] += 1;
}
for(it = mp.begin(); it != mp.end(); it++) {
if(it->second != 3)
return it->first;
}
}
};

这里用到了一种取巧的方法,感觉有违本意。下次再来换下别的方法。

原题:http://oj.leetcode.com/problems/single-number-ii/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: