欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Leetcode 448. Find All Numbers Disappeared in an Array (python+cpp)

程序员文章站 2022-07-15 13:06:14
...

Leetcode 448. Find All Numbers Disappeared in an Array

题目

Leetcode 448. Find All Numbers Disappeared in an Array (python+cpp)

解法:hashmap

利用hashmap的思想,建立一个长度与原数组相等的map数组,map数组中下标代表原数组中的元素值,map数组的元素值代表该下标值在原数组中是否出现。比如原数组[4,3,2,7,8,2,3,1], map数组为[-1,-1,-1,-1,0,0,-1,-1]。遍历一遍map数组即可得到答案
python代码如下:

class Solution:
    def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
        mark = [0]*len(nums)
        for num in nums:
            if mark[num-1] == 0:
                mark[num-1] = -1
        ans = []
        for i in range(len(mark)):
            if mark[i] == 0:
                ans.append(i+1)
        return ans

C++代码如下:

class Solution {
public:
    vector<int> findDisappearedNumbers(vector<int>& nums) {
        vector<int> map(nums.size(),0);
        vector<int> ans;
        for (auto num:nums){
            if (map[num-1]==0) map[num-1]=-1;
        }
        for (int i=0;i<nums.size();i++){
            if (map[i]==0) ans.push_back(i+1);
        }
        return ans;
    }
};