LeetCode 442. Find All Duplicates in an Array
来源:互联网 发布:易吧进销存软件网络版 编辑:程序博客网 时间:2024/06/14 21:11
题目:
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]
思路:
具体思路见注释。
代码:
class Solution {public: vector<int> findDuplicates(vector<int>& nums) { vector<int>ret; if(nums.size()<=1)//如果nums的长度小于等于1,直接返回空vector return ret; int i; for(i=0;i<nums.size();i++){//所有的数减1 nums[i]-=1; } i=0; while(i<nums.size()) { if(nums[i]!=i&&nums[i]!=nums[nums[i]])//将所有数放到对应数值的索引位置 swap(nums[i],nums[nums[i]]); else i++; } for(i=0;i<nums.size();i++) { if(nums[i]!=i)//如果对应索引位置的数不与索引相等 ret.push_back(nums[i]+1);//将刚开始减去的1加上,并push_backt到ret里 } return ret; }};
**输出结果:**149ms
0 0
- [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
- [leetcode] 442. Find All Duplicates in an Array
- LeetCode 442. Find All Duplicates in an Array
- leetcode:442. Find All Duplicates in an Array
- 442. Find All Duplicates in an Array(LeetCode)
- <leetcode>442. Find All Duplicates in an Array
- [leetcode]442. Find All Duplicates in an Array(java)
- [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
- [leetcode]442. Find All Duplicates in an Array
- Leetcode 442. Find All Duplicates in an Array
- LeetCode 442. Find All Duplicates in an Array
- hdu 1116 Play on Words(欧拉图判断模板)
- python学习笔记3
- namenode格式化报错
- Windows安装MySQL5.7.17
- Fragment带参数构造函数时报错解决方法
- LeetCode 442. Find All Duplicates in an Array
- Android Zxing实现二维码扫描功能
- java.util.Set<E>
- linux下的find文件查找命令与grep文件内容查找命令
- SOLID原则
- C# Hook鼠标消息
- C#利用WebClient 两种方式下载文件
- 向量,四元数理解。
- QT 串口通讯