[LeetCode]Find All Duplicates in an Array
来源:互联网 发布:淘宝店铺改名生效 编辑:程序博客网 时间:2024/05/21 12:50
Question
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]
本题难度Medium。
【复杂度】
时间 O(N) 空间 O(1)
【思路】
与[LeetCode]Find All Numbers Disappeared in an Array几乎一样,不同之处就是找出twice的数。那么我们只要当nums[i]!=i+1
时,然后又当nums[nums[i]-1]==nums[i]
时,把nums[i]
放入set即可。
【代码】
public class Solution { public List<Integer> findDuplicates(int[] nums) { //require int size=nums.length; Set<Integer> set=new HashSet<Integer>(); //invariant int i=0; while(i<size){ if(nums[i]!=i+1){ if(nums[nums[i]-1]==nums[i]){ set.add(nums[i]); i++; }else swap(i,nums[i]-1,nums); }else i++; } //ensure return new LinkedList<Integer>(set); } private void swap(int a,int b,int[] nums){ int tmp=nums[a]; nums[a]=nums[b]; nums[b]=tmp; }}
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 (array)
- LeetCode-Find All Duplicates in an Array & Find All Numbers Disappeared 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)
- [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(C++)(
- leetcode 442 Find All Duplicates in an Array C++
- Leetcode 442. Find All Duplicates in an Array
- MemcacheQ 安装和测试
- Android:曲线走势图控件
- (菜鸟教程系列)建造者模式
- Coreldraw图像文件导入PS三种方法
- 日本語:日常会话7-スイーツ【すいーつ】店
- [LeetCode]Find All Duplicates in an Array
- css总结
- 次小生成树模板-prim算法
- 亚马逊账户关联
- 分布式搜索Elasticsearch——QueryBuilders.matchPhraseQuery
- dev自定义排序,CustomColumnSort--------------------学习笔记
- 对于Javascript函数的理解
- cordova-hot-code-push-plugin使用流程
- Number Sequence【规律】