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?

 

数组中的数为1-n,找出出现了2次的数

 

C++(126ms):

 1 class Solution {
 2 public:
 3     vector<int> findDuplicates(vector<int>& nums) {
 4         vector<int> res ;
 5         int len = nums.size() ;
 6         for(int i = 0 ; i < len ; i++){
 7             int t = abs(nums[i]) - 1 ;
 8             if (nums[t] < 0){
 9                 res.push_back(t+1) ;
10             }else{
11                 nums[t] = -nums[t] ;
12             }
13         } 
14         return res ;
15     }
16 };

 

posted @ 2018-01-21 15:31  __Meng  阅读(104)  评论(0编辑  收藏  举报