LeeCode 442. Find All Duplicates in an Array题解
来源:互联网 发布:进击的巨人漫画软件 编辑:程序博客网 时间:2024/06/04 19:15
442. Find All Duplicates in an Array
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?
中文 :给定数组a,1<=a[i]<=n,每个元素至多出现2次,找出出现2次的元素。解 :
因为a的大小也是n,所以如果把a看成抽屉,把抽屉i放元素i+1(下标起始不一致),那么必有抽屉必须放不为i+1的元素,找出这些抽屉输出。
如何找出这些抽屉呢?我们遍历一次数组,每次把元素i放进它对应的位置,遍历完后便有最多元素归位(数学证明略)
代码:
class Solution {public: vector<int> findDuplicates(vector<int>& nums) { vector<int> res; int i = 0; while (i < nums.size()) { if (nums[i] != nums[nums[i]-1]) swap(nums[i], nums[nums[i]-1]); else i++; } for (i = 0; i < nums.size(); i++) { if (nums[i] != i + 1) res.push_back(nums[i]); } return res; }};
阅读全文
0 0
- LeeCode 442. Find All Duplicates in an Array题解
- Find All Duplicates in an Array 题解
- 442. Find All Duplicates in an Array
- 442. Find All Duplicates in an Array
- 442. Find All Duplicates in an Array
- 442. Find All Duplicates in an Array
- 442. Find All Duplicates in an Array
- 442. Find All Duplicates in an Array**
- 442. Find All Duplicates in an Array
- 442. Find All Duplicates in an Array
- 442. Find All Duplicates in an Array
- 442. Find All Duplicates in an Array
- 442. Find All Duplicates in an Array
- 442. Find All Duplicates in an Array
- 442. Find All Duplicates in an Array
- 442. Find All Duplicates in an Array
- 442. Find All Duplicates in an Array
- 442. Find All Duplicates in an Array
- 让我们来谈谈对Linux的认识,值得每一位运维人员深读
- 周末训练笔记+UVA11388+POJ2407+无名题
- 输入输出流的shutdownoutput和shutdowninput方法的使用(文件默认有一个-1的结束标志位)
- LeetCode-116. Populating Next Right Pointers in Each Node【二叉树同层节点构成链表】
- 准备人工智能(未来计划)
- LeeCode 442. Find All Duplicates in an Array题解
- Activity的生命期
- java鬼混笔记:springboot 9、springboot整合mybatis加上分页功能
- python学习笔记-文件操作
- 浅谈unity的NGUI于UGUI的区别
- 文章标题
- Java运算符优先级
- 初学JAVA心得
- 北国秋叶