"Leetcode" Find all Numbers disappeared the problem-solving report in an Array

Source: Internet
Author: User
"Leetcode" Find all Numbers disappeared the problem-solving report in an Array

[Leetcode]

Https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/Total accepted:14302 Total Submissions: 24993 difficulty:easy Question

Given an array of integers where 1≤a[i]≤n (n = size of array),
Some elements appear twice and others appear.

Find all the elements of [1, N] inclusive which does not appear in this
Array.

Could do it without extra spaces and in O (n) runtime? May
Assume the returned list does not count as extra spaces. Example:

Input: [4,3,2,7,8,2,3,1]

Output: [5,6] Ways

At first I did not think of a very effective method, can only use violence to solve. A single method that does not meet the topic without additional space requirements

Method One:

Class Solution (object):
    def finddisappearednumbers (self, Nums): ""
        : Type Nums:list[int]
        : rtype: List[int] ""
        "
        cList = List (range (1, len (nums) + 1))
        returnlist = [] for
        x in Nums:
            clist[x-1] = 0
  for x in CList:
            if x!= 0:
                returnlist.append (x) return
        returnlist

ac:359 ms

Method Two:

Referring to other people's, I learned a way: in situ negative to mark. For example, for [4, 3, 2, 7, 8, 2, 3, 1], these elements as the index of the list, points to the element to transform into a negative, then, there is no change to negative position is no one pointed to it, so this position corresponding subscript did not appear.

Class Solution (object):
    def finddisappearednumbers (self, Nums): ""
        : Type Nums:list[int]
        : Rtype:list[int] "" For
        I in range (len (nums)):
            index=abs (Nums[i])-1
            nums[index]=-ABS (nums[ Index]) return
        [i+1 to I in range (len (nums)) if nums[i] > 0]

ac:362 ms

This speed is still not ideal. Date

January 2, 2017

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.