448. Find All Numbers Disappeared in an Array

这道题目没什么思路,想了好久只是想了个大概,在网上找了找思路,最后将其写出来了
网上对于这道题有几个思路,我选取了一种,排序法
将数组中的元素放到其对应的位置上去,排好序后,在遍历一遍,最终加入到返回数组里面去

题目:Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.

Find all the elements of [1, n] inclusive that do not appear in this array.

Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.

这里面有几个需要注意的地方,

  • 数组里面每个数的范围是[1, n]
  • 返回的数组不算在额外空间复杂度里面去
  • 将数组元素当作下标
class Solution {
   public List<Integer> findDisappearedNumbers(int[] nums) {
       List<Integer> list = new ArrayList<>();
       //将数组中的数。放到对应位置去
       for (int i = 0; i < nums.length; ++i) {
           //这里面的第二个判断,保证换过来的数不相等,否则会一直卡在这里
           if (nums[i]-1 != i && nums[nums[i]-1] != nums[i]) {
               swap(nums, nums[i]-1, i);//让数组中的每个数字,应该在其对应位置上
               --i;//换过来的数,可能不在这个位置,需要对这个位置再判断一下
           }
       }
       for (int i = 0; i < nums.length; i++) {
           if (nums[i]-1 != i) {//如果对应位置上不相等,就把应该放到的数,放进去
               list.add(i+1);
           }
       }
       return list;
   }

   public void swap(int[] nums, int i, int j) {
       int tmp = nums[i];
       nums[i] = nums[j];
       nums[j] = tmp;
   }
}
 if (nums[i]-1 != i && nums[nums[i]-1] != nums[i])
 第一个语句是判断数组对应位置与数是不是一样的,
 第二个是判断交换过来的数是不是相等

与这道题思路相似的题目有

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值