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?
Example:
题目大意:
给定一个整数数组,1 <= a[i] <= n (n = 数组长度),某些元素出现两次,某些出现一次。寻找数组中所有出现两次的元素。你可以不使用额外空间并且在O(n)运行时间内完成题目吗?
解题思路:
方法1 hashmap
方法2 正负号标记法
when find a number i, flip the number at position i-1 to negative. if the number at position i-1 is already negative, i is the number that occurs twice.class
Last updated
Was this helpful?