LeetCode--Single Number III

来源:互联网 发布:直通车关键字优化 编辑:程序博客网 时间:2024/06/04 18:04

题目:

Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.

For example:

Given nums = [1, 2, 1, 3, 2, 5], return [3, 5].

Note:

  1. The order of the result is not important. So in the above example, [5, 3] is also correct.
  2. Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?
代码:

    vector<int> singleNumber(vector<int>& nums) {        unordered_map<int, bool> a;        int b = 0;        vector<int> c;        for(int i = 0; i < nums.size(); ++i)        {            if(!a.count(nums[i]))            {                a[nums[i]] = true;            }            else //删除所有出现两次的数,并统计个数            {                a.erase(nums[i]);                ++b;            }        }        for(int j = 0; j < nums.size()-2*b; ++j) <span style="font-family: Arial, Helvetica, sans-serif;">//将剩下的数的第一个加入vec,再从map中删除,如同stack的pop</span>        {            c.push_back(a.begin()->first);            a.erase(a.begin()->first);        }        return c;            }


0 0