Find All Duplicates in an Array
来源:互联网 发布:文件夹隐藏加密软件 编辑:程序博客网 时间:2024/05/17 06:32
题目描述:
给定一个整型数组 ,
找出所有出现两次的数组元素。 时间复杂度O(n),额外的空间复杂度O(1)。
题目分析:
该题目的难点在于对时间和空间复杂度的要求,要想达到目标必须充分利用好原始空间和已知条件。
注意到数组元素取值与数组下标有对应关系。 如果我们把元素安放到元素值对应数组索引位置,即把a[i]放到 aa[i]-1位置,在这个过程中如果发现本来就有 a[a[i]-1] = a[i] 的话,则a[i]这个值必定出现两次,所以只要保存这些值就可以了。
下面举例说明算法的过程:
已经有序列:
[1 2 2 4 5 6 3 3]
从头开始检查数组值是否与对应下标相等, a[0], a[1],都符合新条件
a[2]移动到a[1]发现a[1]本来已经符合条件了,所以把2 加入结果,并设置当前a[2] =-1(置空)
a[3] a[4] a[5] 都符合条件,a[6] ,a[2]交换值,a[2]已经变成-1空了,继续判断a[7],这时发现a[2]已经放了合适的元素,所以将3加入结果。
最后打印
[ 2 3]
代码实现:
class Solution {public: vector<int> findDuplicates(vector<int>& nums) { //sort the vector vector<int> resul; int j =0; for(int i =0 ; i <nums.size() ; ++i) { while(nums[i]!=-1&&nums[i]!=(i+1)){ j = nums[nums[i]-1]; if( nums[nums[i]-1]== nums[i]) { resul.push_back(nums[i]); nums[i] = -1 ; break; } nums[nums[i]-1] = nums[i]; nums[i] = j ; } } return resul; }};
0 0
- 442. Find All Duplicates in an Array
- [LeetCode]Find All Duplicates in an Array
- LeetCode Find All Duplicates in an Array
- Leetcode442. Find All Duplicates in an Array
- 442. Find All Duplicates in an Array
- 442. Find All Duplicates in an Array
- Find All Duplicates in an Array
- 442. Find All Duplicates in an Array
- Leetcode Find All Duplicates in an Array
- 442. Find All Duplicates in an Array
- [Leetcode] Find All Duplicates in an Array
- 442. Find All Duplicates in an Array**
- leetcode_middle_6_442. Find All Duplicates in an Array
- 442. Find All Duplicates in an Array
- 442. Find All Duplicates in an Array
- Find All Duplicates in an Array
- 442. Find All Duplicates in an Array
- Find All Duplicates in an Array 题解
- 如何在spark-streaming中获取通过kafka传递的flume信息header
- android studio如何添加插件
- mysql float的缺点 (不适用于高精度数据)
- Oracle Index Clustering Factor(集群因子)
- gtest笔记 ---测试类中的函数
- Find All Duplicates in an Array
- 基于Fusioncharts的报表统计
- C++中main()函数中argc和argv的含义
- IaaS、PaaS、SaaS三类模式应用示意图
- lua 产生随机数
- 仿QQ左拉删除
- MVC的composer
- 数学系列:数学在计算机图形学中的应用
- 网络客户端