[LeetCode]448. Find All Numbers Disappeared in an Array 解题报告(C++)

[LeetCode]448. Find All Numbers Disappeared in an Array 解题报告(C++)

题目描述

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.

Example:

Input:
[4,3,2,7,8,2,3,1]

Output:
[5,6]

题目大意

  • 给定一个数组. 数组中的元素 1<=a[i]<=n n是数组的长度.
  • 有一些数字出现了两次.有些数字消逝了.
  • 找到这些数字.
  • 要求不能使用额外空间 & 时间复杂度 O(n)

解题思路

方法1:

  • 暴力方法.使用了额外空间! 时间O(n)
  • 思路正确:
  • 就是将 a[i] 放到它排序之后应该在的位置.
  • 注意:索引 ia[i] 的关系
代码实现:
class Solution1 {
public:
    vector<int> findDisappearedNumbers(vector<int>& nums) {
        int size = nums.size();
        // 开辟一个也是n的空间.并初始化为0
        vector<int> index(size, 0);
        for (int i = 0; i < size; i++) {
            // 当nums[i]这个数应在放的位置没有数字的时候!放上去!
            if (index[nums[i] - 1] == 0) {
                index[nums[i] - 1]++;
            }
        }
        vector<int> res;
        for (int i = 0; i < size; i++) {
            // 找到0的索引.将其加入结果
            if (index[i] == 0) {
                res.push_back(i + 1);
            }
        }
        return res;
    }
};

方法2:

  • 延续了方法1的思路. nums[i]应该放到它应该在的位置.
  • 考虑两种情况:
    • nums[i] 已经在应在的位置.
    • 应该有的位置已经有值了. 即重复的情况.
代码实现:
class Solution2 {
public:
    vector<int> findDisappearedNumbers(vector<int>& nums) {
        int size = nums.size();
        for (int i = 0; i < size; ) {
            int j = nums[i]-1; // j表示应该在的位置
            if (j== i) { // 已经在应在的位置了.
                i++;
            }
            else if (nums[j] != nums[i]) { // 不重复,则交换
                swap(nums[j], nums[i]);
            }
            else { // 该有的位置有了正确值了.则将这个值坐下标记0.遍历下一个.
                nums[i] = 0;
                i++;
            }
        }

        vector<int> res;
        for (int i = 0; i < size; i++) {
            if (nums[i] == 0) { // 找到值为0的索引.
                res.push_back(i+1);
            }
        }
        return res;
    }
};

小结

  • 注意 索引i 与 arr[i] 的关系! 往往是解题的关键.
  • 针对一个问题可以先提出非常暴力的方法.再不断的优化.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值