Leetcode 442-Find All Duplicates in an Array
来源:互联网 发布:mac命令行终端 编辑:程序博客网 时间:2024/05/16 05:36
Given an array of integers, 1 ≤ a[i] ≤ n (n = size ofarray), 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]
题目的意思是给定一个长度为n的整数数组,数组中的元素1 ≤ a[i] ≤ n,有些元素出现一次,有些出现两次,让我们找出出现两次的元素。题目要求不开辟额外空间来实现时间复杂度O(n)的方法。
之前做过类似的题目,时间复杂度O(n),所以只能从头到尾遍历一次,不能做排序等操作。题目要求不能开辟额外空间,既然给定的数组中元素x都是介于1-n之间的,而数组正好也有n个元素,我们正好可以用a[x]的正负性来标记x是否出现过。将出现过一次的元素x,对应的a[x]标记为负。这题目的思路和 Leetcode 448. Find All NumbersDisappeared in an Array中的方法3思路很像,只不过448中我们是将出现过的元素x,对应的a[x]标记为负。
class Solution {public: vector<int> findDuplicates(vector<int>& nums) { vector<int>re; for(int x:nums) { if(nums[abs(x)-1]<0) re.push_back(abs(x)); else nums[abs(x)-1]*=-1; } return re; }};
阅读全文
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
- javascript简单计算器
- Swagger工具详解
- Bootstrap(十七)
- plsql安装提示Warning: Some Oracle Net versions cannot connect
- 生活小记68
- Leetcode 442-Find All Duplicates in an Array
- Bootstrap(十八)
- 程序员面试宝典随笔记(一)----define和const
- Latex 中文配置解析
- Java--集合--WeakHashMap
- linux 服务器日志查看
- python基础知识巩固(一)——字符串
- Ubuntu 16.04 pycharm设置桌面快捷启动方式
- 《写给大家看的设计书(第3版)》【PDF】下载