题目描述:
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]
解题思路:
看到数据给定范围,想到桶排序。
要求不能使用额外空间,这点有点弄不明白,不知道我这算不算使用额外空间。
代码:
1 class Solution { 2 public: 3 vector<int> findDuplicates(vector<int>& nums) { 4 vector<int> ret (nums.size(), 0); 5 for (auto num : nums) { 6 ret[num-1]++; 7 } 8 int i = 0, j = 0; 9 for (; i < nums.size(); i++) { 10 if (ret[i] == 2) 11 ret[j++] = i+1; 12 } 13 ret.resize(j); 14 return ret; 15 } 16 };