zoukankan      html  css  js  c++  java
  • [Array]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.

    Example:

    Input:
    [4,3,2,7,8,2,3,1]
    
    Output:
    [5,6]

    思路:给出长度为n的数组,遍历所有元素,找出没有出现过的元素。基本思想是我们将元素值作为下标遍历输入数组并标记为负值num[i] = -num[i]。
    vector<int> finddisappear(vector<int>& nums){
    vector<int>tmp;
    size_t n = nums.size();
    for(size_t i = 0; i < n; i++){
    int val = abs(nums[i]) - 1;//nums[i]是所有元素值,val是下标,将元素值出现的下标的元素标记为负值,减1的意思是下标比个数少1
    if(nums[val] > 0)
    nums[val] = -nums[val];
    }
    
    for(size_t i = 0; i < n; i++){
    if(nums[i] > 0)
    tmp.push_back(i + 1);
    }
    return tmp;
    }
    比如4个元素的数组里出现了2,3,那么下标为2,3的元素标为负值,剩下的1,4没有出现,那么仍为正值,找到正值的下标也就是结果了。
  • 相关阅读:
    防抖、节流函数
    vue如何监听数组的变化
    scss的循环和数组
    linux更新node版本
    函数节流和防抖函数
    vue-cli 使用,更新
    webstorm自动编译scss
    git冲突的处理
    linuix 安装 mysql8
    脚本安装mysql 8
  • 原文地址:https://www.cnblogs.com/qinguoyi/p/7280212.html
Copyright © 2011-2022 走看看