forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[Array] Add a solution to Find All Numbers Disappeared in an Array
- Loading branch information
Showing
1 changed file
with
30 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
/** | ||
* Question Link: https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/ | ||
* primary idea: Traverse the array and get num really position in array, then set negative. | ||
* In the final, filter greater than 0 num. | ||
* | ||
* Time Complexity: O(n), Space Complexity: O(1) | ||
* | ||
*/ | ||
|
||
class FindDisappearedNumbers { | ||
func findDisappearedNumbers(_ nums: [Int]) -> [Int] { | ||
var nums = nums | ||
var result = [Int]() | ||
|
||
for i in 0..<nums.count { | ||
let index = abs(nums[i]) - 1 | ||
if nums[index] > 0 { | ||
nums[index] = -nums[index] | ||
} | ||
} | ||
|
||
for i in 0..<nums.count { | ||
if nums[i] > 0 { | ||
result.append(i+1) | ||
} | ||
} | ||
|
||
return result | ||
} | ||
} |