442. Find All Duplicates in an Array
2017-01-06 23:26
148 查看
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:
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> result; for (int i = 0; i < nums.size(); i++) { while (nums[i] != -1 && i != nums[i] - 1) { if (nums[i] == nums[nums[i] - 1]) { result.push_back(nums[i]); nums[i] = -1; break; } swap(nums[i], nums[nums[i] - 1]); } } return result; } };
相关文章推荐
- ruby 数组使用教程
- Ruby中的数组和散列表的使用详解
- C#实现AddRange为数组添加多个元素的方法
- C#比较二个数组并找出相同或不同元素的方法
- 快速解决C# android base-64 字符数组的无效长度问题
- C#中数组、ArrayList和List三者的区别详解
- C# 拷贝数组的几种方法(总结)
- C#动态调整数组大小的方法
- 详解Lua中的数组概念知识
- Perl中的列表和数组学习笔记
- jQuery 判断是否包含在数组中Array[]的方法
- 浅谈C#各种数组直接的数据复制/转换
- 探索PowerShell (八) 数组、哈希表(附:复制粘贴技巧)
- C#中数组初始化与数组元素复制的方法
- Bash中数组的操作教程
- C#交错数组用法实例
- Linux Shell 数组建立及使用技巧
- PowerShell数组的一些操作技巧
- C#通过yield实现数组全排列的方法
- C#不重复输出一个数组中所有元素的方法