"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