LeetCode 448 找到所有数组中消失的数字 HERODING的LeetCode之路

给定一个范围在 1 ≤ a[i] ≤ n ( n = 数组大小 ) 的 整型数组,数组中的元素一些出现了两次,另一些只出现一次。

找到所有在 [1, n] 范围之间没有出现在数组中的数字。

您能在不使用额外空间且时间复杂度为O(n)的情况下完成这个任务吗? 你可以假定返回的数组不算在额外空间内。

示例:

输入:
[4,3,2,7,8,2,3,1]

输出:
[5,6]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-all-numbers-disappeared-in-an-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解题思路:
本次方法使用最朴素的方法,就是将出现的数字统计下来,再重新遍历一下,因为一共就n种数,数的最大为n,所以把1——n没有出现的数字保存下来即可,代码如下:

class Solution {
    
    
public:
    vector<int> findDisappearedNumbers(vector<int>& nums) {
    
    
        vector<int> ans;
        // 如果数组大小为0
        if(nums.empty() == true) {
    
    
            return ans;
        }
        vector<int> count(nums.size() + 1, 0);
        // 遍历数组统计出现的元素
        for(int i = 0; i < nums.size(); i ++) {
    
    
            count[nums[i]] ++;
        }
        // 遍历count保存未出现的元素
        for(int i = 1; i <= nums.size(); i ++) {
    
    
            if(count[i] == 0) {
    
    
                ans.push_back(i);
            }
        }
        return ans;
    }
};


/*作者:heroding
链接:https://leetcode-cn.com/problems/find-all-numbers-disappeared-in-an-array/solution/zui-xiang-xi-zhu-jie-by-heroding-loi2/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。*/

猜你喜欢

转载自blog.csdn.net/HERODING23/article/details/113799220