LeetCode - 442. Find All Duplicates in an Array - 几种不同思路 - (C++)
2016-11-17 09:44
369 查看
题目
题目链接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 ≤ a[i] ≤ n ,n是数组的元素个数。一些元素出现了两次,而其它元素只出现了一次。
找出那些出现了两次的元素。要求没有占用额外的空间而且时间复杂性为 O(n) 。
例如:
输入:
[4,3,2,7,8,2,3,1]
输出:
[2,3]
思路
(不想看其它思路的可以直接跳到第三个)其实本来一开始想到的实现方法是hash table的,但是如各位所知,hash table对空间还是有要求的,因此其实不符合题意,权当写着玩了。hash table的solution如下,runtime一般:
class Solution { public: vector<int> findDuplicates(vector<int>& nums) { int m=nums.size(),n; int s[m]; vector<int> ans; memset(s,0,m*4); for(int i=0;i<m;i++) { n=nums[i]-1; s ++; } for(int i=0;i<m;i++) if(s[i]>1) ans.push_back(i+1); return ans; } };
第二个想法,先排序,再判断。runtime比较差,但空间占用少。
class Solution { public: vector<int> findDuplicates(vector<int>& nums) { int m=nums.size(),n; vector<int> ans; stable_sort(nums.begin(),nums.end(),[](const int& x,const int& y){return x<y;}); for(int i=0;i<m;i++) if(nums[i]==nums[i+1]) {ans.push_back(nums[i]);i++;} return ans; } };
第三个想法,先归位,没在位置上的就是重复的数字。这个solution比之前的两个runtime表现都要好。
class Solution { public: vector<int> findDuplicates(vector<int>& nums) { int m=nums.size(),n; vector<int> ans; for(int i=0;i<m;) if(nums[nums[i]-1]!=nums[i]) swap(nums[i],nums[nums[i]-1]); else i++; for(int i=0;i<m;i++) if(nums[i]!=i+1) ans.push_back(nums[i]); return ans; } };
相关文章推荐
- LeetCode - 136. Single Number - ( C++ ) - 解题报告 - 位运算思路 xor
- LeetCode - 459. Repeated Substring Pattern - O(n)和O(n^2)两种思路 - KMP - (C++) - 解题报告
- LeetCode-219. Contains Duplicate II-思路详解-C++
- LeetCode - 153. Find Minimum in Rotated Sorted Array - 思路详解- C++
- LeetCode - 162. Find Peak Element - 思路详解 - C++
- C++中几种不同交换两个数的方法
- LeetCode - 462. Minimum Moves to Equal Array Elements II - 思路详解 - C++
- LeetCode- 169. Majority Element - 思路详解 -C++
- LeetCode- 238. Product of Array Except Self - 思路详解 -C++
- LeetCode - 401. Binary Watch - 思路详解-C++
- Leetcode-448. Find All Numbers Disappeared in an Array-思路详解 - C++
- LeetCode- 1. Two Sum - 思路详解-C++
- LeetCode- 167. Two Sum II - Input array is sorted - 思路详解- C++
- LeetCode - 228. Summary Ranges - 思路详解- C++
- LeetCode - 482. License Key Formatting - 思路详解 -C++
- LeetCode - 389. Find the Difference - 三种不同解法 - ( C++ ) - 解题报告
- LeetCode-399. Evaluate Division-思路详解-C++
- LeetCode-386. Lexicographical Numbers-思路详解-C++
- LeetCode - 216. Combination Sum III - 思路详解 - C++
- LeetCode -485. Max Consecutive Ones - 思路详解 - C++