题目来源 点击打开链接
题目详情
Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements that appear twice in this array.
题目解答Could you do it without extra space and in O(n) runtime?
Example:
Input: [4,3,2,7,8,2,3,1] Output: [2,3]
class Solution { public: vector<int> findDuplicates(vector<int>& nums) { int leng = nums.size(); map<int, bool> twice; vector<int> ret; for(int i = 0; i < leng; i++){ map<int, bool>::iterator it; it = twice.find(nums[i]); if(it != twice.end()) twice[nums[i]] = 1; else{ twice[nums[i]] = 0; } } map<int, bool>::iterator itr; itr = twice.begin(); for(; itr!=twice.end(); itr++){ if((*itr).second) ret.push_back((*itr).first); } return ret; } };