[LeetCode] Single Number II

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(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/

posted on 2013-10-19 23:25  風逍遥  阅读(130)  评论(0编辑  收藏  举报

导航