Leetcode 442 - Find All Duplicates in an Array (array)
来源:互联网 发布:el表达式获取js变量 编辑:程序博客网 时间:2024/06/04 17:45
题意
同448,但是要求找出出现了两次的元素。
思路
算法1
还是特别trick的一道题,但是既然写了448,我们大致就可以围绕那个方向了。
我们还是假设x出现了,我们另a[abs(x) - 1]变为负数,代表x出现了一次。
但是如果x出现了两次呢?要是我们再取一次反的话,就和没有出现的没有区别了。
然后我的想法是如果y = a[abs(x) - 1]本身已经为负数了,说明已经出现了一次,将y减小n即可。
如果遇到x小于-n,说明x出现了两次,我们只需要+n就可以进行下一个索引。
其实,按照这个思路,我们就可以判断出现3,4,5次了。
算法2
如果x首先出现,我们将a[abs(x) - 1]变为负数。
如果x再次出现,那么a[abs(x) - 1]一定已经是负数,我们将其加入答案即可。
算法3
交换元素法。
我们这样想,我们如果每个数都只出现1次,那么我们的元素一定可以经过某些交换,使nums[i - 1] = i
。
如果一些数出现两次,那么就会导致没有出现的数的那些位置为nums[i - 1] != i
,并且该位置上的nums[i - 1]
即为我们出现两次的数。
然后我们的交换策略为:如果nums[i] != nums[nums[i] - 1]
,那么交换这两个位置上的数,实际上做的就是使nums[i - 1] = i
。
因为重复出现的数最多出现两次,所以我们可以保证时间复杂度仍为
代码
//algorithm1class Solution {public: vector<int> findDuplicates(vector<int>& nums) { int n = nums.size(); for (auto x : nums) { if (x < -n) x += n; if (nums[abs(x) - 1] > 0) nums[abs(x) - 1] = -nums[abs(x) - 1]; else nums[abs(x) - 1] -= n; } vector<int> ans; for (int i = 0; i < n; i++) { if (nums[i] < -n) ans.push_back(i + 1); } return ans; }};//algorithm 2class Solution {public: vector<int> findDuplicates(vector<int>& nums) { vector<int> ans; for (auto x : nums) { if (nums[abs(x) - 1] < 0) ans.push_back(abs(x)); else nums[abs(x) - 1] = -nums[abs(x) - 1]; } return ans; }};//algorithm 3class Solution {public: vector<int> findDuplicates(vector<int>& nums) { vector<int> ans; for (int i = 0; i < nums.size(); i++) { if (nums[i] != nums[nums[i] - 1]) { swap(nums[i], nums[nums[i] - 1]); i--; } } for (int i = 0; i < nums.size(); i++) { if (nums[i] != i + 1) ans.push_back(nums[i]); } return ans; }};
0 0
- Leetcode 442 - Find All Duplicates in an Array (array)
- [LeetCode]Find All Duplicates in an Array
- LeetCode Find All Duplicates in an Array
- Leetcode Find All Duplicates in an Array
- [Leetcode] Find All Duplicates in an Array
- leetCode-Find All Duplicates in an Array
- [C语言][LeetCode][442]Find All Duplicates in an Array
- 【LeetCode-442】Find All Duplicates in an Array(C++)(
- leetcode 442 Find All Duplicates in an Array C++
- [LeetCode]442 Find All Duplicates in an Array
- LeetCode 442 --- Find All Duplicates in an Array
- [leetcode 442] Find All Duplicates in an Array
- LeetCode 442 Find All Duplicates in an Array
- Find All Duplicates in an Array,leetcode,442
- LeetCode.442 Find All Duplicates in an Array
- Leetcode 442-Find All Duplicates in an Array
- 【442】Find All Duplicates in an Array
- LeetCode-Find All Duplicates in an Array & Find All Numbers Disappeared in an Array
- pms
- LeetCode 40. Combination Sum II
- 信息学算法初步
- PHP源代码数组统计count分析
- AltiumDesign多层板设计
- Leetcode 442 - Find All Duplicates in an Array (array)
- [oracle] 常用函数merge
- Windows C++界面库
- DOM遍历
- LeetCode 78. Subsets
- 优化Group By语句
- 简单的及其水的A+B
- 56. Merge Intervals
- Windows下搭建PHP开发环境