leetcode(16)

leetcode(16)

442. Find All Duplicates in an Array

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) {
 sort(nums.begin(),nums.end());
 vector<int> res;
 int size=nums.size();
 for(int i=0;i<size-1;i++)
 if(nums[i]==nums[i+1])
 {
 res.push_back(nums[i]);
 i++;
 }
 return res;
 }
};



So BadJust So SoGoodCoolPretty Cool (还没人评过分呢!)
Loading...

发表评论

电子邮件地址不会被公开。 必填项已用*标注