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

    solution:
     1 class Solution {
     2 public:
     3     vector<int> findDisappearedNumbers(vector<int>& a) 
     4     {
     5         vector<int> vecDisappear;vecDisappear.clear();
     6         int n = a.size();
     7         for(int i = 0;i<n;)
     8         {
     9           if(a[i] != a[a[i]-1])
    10           {
    11               swap(a[i],a[a[i]-1]);
    12           }
    13           else
    14            i++;
    15         }
    16         for(int i = 0;i<n;i++)
    17         {
    18             if(a[i]!=i+1)
    19             {
    20                 vecDisappear.push_back(i+1);
    21             }
    22         }
    23         return vecDisappear;
    24 }

    思路:遍历vector,对于i上的数字而言,确保其上出现的数字a[i]已经出现在正确的位置a[a[i]-1]上,否则交换二者位置。

    solution2:

    class Solution {
    public:
        vector<int> findDisappearedNumbers(vector<int>& a) 
        {
            vector<int> vecDisappear;vecDisappear.clear();
            for(int i = 0;i<a.size();i++)
            {
                auto index = abs(a[i])-1;
                if(a[index]>0)
                {
                    a[index]=-a[index];
                }
            }
            for(int i = 0;i<a.size();i++)
            {
                if(a[i]>0)
                 vecDisappear.push_back(i+1);   
            }
            return vecDisappear;
        }
    };

    思路:对于i上出现的数字a[i],即表示索引a[i]-1位置上的数字已成功出现。

  • 相关阅读:
    江西师范大学瑶湖校区图片
    什么是sp?
    教育技术学硕士点学校排名
    西南师大教育技术学专业2005年入学考试信息
    什么是"工包"?
    买书网址
    2006年全国教育技术学专业新增硕士点
    今天终于拿到书了
    2007年教育学专业基础综合考试大纲(重要部分) ——下载地址
    电脑DIY推荐
  • 原文地址:https://www.cnblogs.com/Swetchine/p/11185754.html
Copyright © 2011-2022 走看看