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 };
原文地址:https://www.cnblogs.com/mengchunchen/p/8324399.html