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?
Example:
Input:
[4,3,2,7,8,2,3,1]
Output:
[2,3]
解法一
判断数组的中的某一项值是否已经发生变化。如num[i]=7, 对7-1=6,num[6]的位置发生变化,如果7只出现一次,则num[6]变化一次;如果7只出现两次,而num[6]已经发生了变化,则找到原来的值6+1.
public class Solution {
public List<Integer> findDuplicates(int[] nums) {
List<Integer> ret = new ArrayList<>();
if (nums == null || nums.length == 0) {
return ret;
}
int len = nums.length;
for (int i = 0; i < nums.length; i++) {
int index = (nums[i] - 1) % len;
if (nums[index] > len) {
ret.add(index + 1);
} else {
nums[index] += len;
}
}
return ret;
}
}
解法二
判断某一项是否为负数。
public class Solution {
public List<Integer> findDuplicates(int[] nums) {
List<Integer> ret = new ArrayList<>();
if (nums == null || nums.length == 0) {
return ret;
}
for (int i = 0; i < nums.length; i++) {
int index = Math.abs(nums[i]) - 1;
if (nums[index] < 0) {
ret.add(index + 1);
} else {
nums[index] *= -1;
}
}
return ret;
}
}
数组中重复数字查找
本文介绍了一种在不使用额外空间且时间复杂度为O(n)的情况下找出数组中所有重复数字的方法。通过两种不同的实现方式:一是改变数组元素值来标记已访问的状态,二是利用负数标记已经检查过的元素。
358

被折叠的 条评论
为什么被折叠?



