Algorithm
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]
题意:给一个数组,且1<=a[i]<=n (n为数组的元素大小),数组中有一些出现两次的元素,也有出现一次的元素。找出所有出现两次的元素。
思路:我自己是没有任何思路,看到评论的题解如下。这里加粗的条件非常重要,可以确保a[a[i]-1]合法。
题解一
//遍历数组,可以是a[i]对应的a[a[i]-1]位置的数变为-a[a[i]-1],那么如果第二次遇到前面相同的数字时,就有a[i]<0。那么这就可以找出来了。
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(index+1);
nums[index] = -nums[index];
}
return res;
}
}
题解二
//遍历nums数组,如果nums[i]和nums[nums[i]-1]不相等,那么交换,如果相等则i++
//这么做的目的是为了把每个数字都放到对应nums[i]-1的位置,那么最终不再nums[i]-1位置的,即为重复的数字。
class Solution {
public:
vector<int> findDuplicates(vector<int>& nums) {
vector<int> res;
int i = 0;
while (i < nums.size()) {
if (nums[i] != nums[nums[i]-1]) swap(nums[i], nums[nums[i]-1]);
else i++;
}
for (i = 0; i < nums.size(); i++) {
if (nums[i] != i + 1) res.push_back(nums[i]);
}
return res;
}
};
Review
学习繁忙以后再补。