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]

    给出n个数,其中1~n中有些数没出现,求这些没出现的数。

    我们可以将数值和数组的标关联,运用负号巧妙的解决了这个问题。确保每个出现过的数都变成负数

    class Solution {
    public:
        vector<int> findDisappearedNumbers(vector<int>& nums) {
            vector<int> v;
            for (int i = 0; i < nums.size(); ++i) {
                int index = abs(nums[i]) - 1;
                nums[index] = -abs(nums[index]);
                
            }
            for (int i = 0; i < nums.size(); ++i) {
                if (nums[i] > 0) v.push_back(i + 1);
            }
            return v;
        }
    };
  • 相关阅读:
    LinkLabel控件使用
    读取mysql代码片段
    设置点风格
    C# List 用法
    图片焦点图切换效果
    dreamweaver 泛泛之谈
    js 之for..in、表单及事件触发
    实现省份查询 功能
    input类主要是
    js (1)
  • 原文地址:https://www.cnblogs.com/pk28/p/7250740.html
Copyright © 2011-2022 走看看