首页 > 代码库 > 442. Find All Duplicates in an Array
442. Find All Duplicates in an Array
<style>p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px "Helvetica Neue"; color: #323333 }
p.p2 { margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px "Helvetica Neue"; color: #323333; min-height: 16.0px }
p.p3 { margin: 0.0px 0.0px 0.0px 0.0px; font: 13.0px Menlo; color: #323333; background-color: #f5f5f5 }
p.p4 { margin: 0.0px 0.0px 0.0px 0.0px; font: 13.0px Menlo; color: #323333; background-color: #f5f5f5; min-height: 15.0px }
span.s1 { }</style>
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]
idea: similar methods with 448 Find All Numbers Disappeared in an Array
Solution 1: If nums[index] is already <0, index+1 is the duplicated number
1 class Solution { 2 public: 3 vector<int> findDuplicates(vector<int>& nums) { 4 int n=nums.size(); 5 vector<int> res; 6 for (int i=0;i<n;i++){ 7 int index=abs(nums[i])-1; 8 if (nums[index]<0) res.push_back(abs(nums[i])); //diff with 448 9 else nums[index]=-nums[index]; 10 } 11 return res; 12 } 13 };
Solution 2: If nums[i]!= i+1, nums[i] is the duplicated number.
1 class Solution { 2 public: 3 vector<int> findDuplicates(vector<int>& nums) { 4 int n=nums.size(); 5 vector<int> res; 6 for (int i=0;i<n;i++){ 7 int index=nums[i]-1; 8 if (nums[index]!=nums[i]) { 9 swap (nums[i],nums[index]); 10 --i; 11 } 12 } 13 for (int i=0;i<n;i++){ 14 if (nums[i]!=i+1) res.push_back(nums[i]); //diff with 448 15 } 16 return res; 17 } 18 };
Solution 3: If nums[i]>2*n, i+1 is the duplicated number.
1 class Solution { 2 public: 3 vector<int> findDuplicates(vector<int>& nums) { 4 int n=nums.size(); 5 vector<int> res; 6 for (int i=0;i<n;i++){ 7 nums[(nums[i]-1)%n]+=n; 8 } 9 for (int i=0;i<n;i++){ 10 if (nums[i]>2*n) res.push_back(i+1); //diff with 448 11 } 12 return res; 13 } 14 };
442. Find All Duplicates in an Array
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。