您的位置:首页 > 其它

leetcode -- 442. Find All Duplicates in an Array 【数组随机性 + 数据特点 + 整数符号位使用】

2017-07-03 22:27 267 查看

题目

Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appeartwice and others appearonce.

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]

题意

给定一个整型数组,整型数组中的元素范围为 1 <= a[ i ] <= n ,一些元素出现了两次,一些出现了一次。找出所有出现两次的元素。

分析及解答

解法1:

【两个限制】 (1)整型范围,因为整型范围较小,所以我们可以借助数组能够随机访问的优势;(2)出现次数,出现次数是固定的数字,所以我们可以简化重复的判断的条件。
【缺陷】未能在不借助辅助空间的情况下实现该算法。

public class Solution {
public List<Integer> findDuplicates(int[] nums) {
List<Integer> duplicates = new LinkedList<>();
int[] results = new int[nums.length + 1 ];
for(int num : nums){
results[num]++;
}

for(int i = 1; i < results.length;i++){
if(results[i] == 2){
duplicates.add(i);
}
}
return duplicates;

}
}


解法2:(利用限制)

【巧妙利用限制】前面提到了两个限制,解法2 利用出现的数字均为正整数这个限制,利用其作为一次计数的标志。因为是正整数,所以我们符号位便没有充分利用起来,另外因为每个数字最多出现两次,所以我们可以将负号作为标志,记作一次计数。于是就得到了下面的做法。

【局限】该解法与题目耦合性很强,不具有普适性。

public class Solution {
// 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.

public List<Integer> findDuplicates(int[] nums) {
List<Integer> res = new ArrayList<>();
for (int i = 0; i < nums.length; ++i) {
int index = Math.abs(nums[i])-1;
if (nums[index] < 0)
res.add(Math.abs(index+1));
nums[index] = -nums[index];
}
return res;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法 leetcode medium
相关文章推荐