我在leetcode网站上做的算法题,在讨论里找到的好算法,在这里分享一下。
源码如下
import java.util.*;
public class Solution {
public List<Integer> findDisappearedNumbers(int[] nums) {
List<Integer> ret = new ArrayList<Integer>();
for(int i = 0; i < nums.length; i++) {
int val = Math.abs(nums[i]) - 1;
if(nums[val] > 0) {
nums[val] = -nums[val];
}
}
for(int i = 0; i < nums.length; i++) {
if(nums[i] > 0) {
ret.add(i+1);
}
}
return ret;
}
}
算法介绍:
The basic idea is that we iterate through the input array and mark elements as negative using nums[nums[i] -1] = -nums[nums[i]-1]
. In this way all the numbers that we have seen will be marked as negative. In the second iteration, if a value is not marked as negative, it implies we have never seen that index before, so just add it to the return list.
即:我的基本思想是:先遍历数组,使用 nums[nums[i] -1] = -nums[nums[i]-1] 来将数组元素标记为负数(即原来数字的相反数)。用这种方式来将所有我们已经看到的数字标记为负数。在第二次迭代的时候,如果数组对应值不是负数,则可以推断出我们之前从来没有看到过这个索引,因此将它添加到列表中。