448. 找到所有数组中消失的数字
只需要将出现的数转化成索引,并且修改数组中对应索引的值为负数,最后遍历看哪些数是正数,说明其对应索引加1的数没出现过
class Solution { public List<Integer> findDisappearedNumbers(int[] nums) { for (int i = 0; i< nums.length; i++) { //用当前数计算索引值 int index = Math.abs(nums[i])-1; //将对应索引位置的数改成负的 nums[index] = -Math.abs(nums[index]); } //遍历结束,没有变成负数的就是没出现过的 List<Integer> res = new ArrayList<>(); for(int i = 0;i<nums.length;i++){ if(nums[i] > 0){ //i是索引,要加1 res.add(i+1); } } return res; } }