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没有出现,那么仍为正值,找到正值的下标也就是结果了。
  • 相关阅读:
    C#文件操作
    C#Web编程
    WMsg参数常量值
    IIS管理网站浏览
    课程视频网址
    CSS 学习质料
    Centos镜像使用帮助
    apache ab压力测试报错(apr_socket_recv: Connection reset by peer (104))
    How to Configure Nginx for Optimized Performance
    luarocks install with lua5.1 and luajit to install lapis
  • 原文地址:https://www.cnblogs.com/qinguoyi/p/7280212.html
Copyright © 2011-2022 走看看