forked from super30admin/Array-2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDisappearedNumbers.java
More file actions
31 lines (26 loc) · 1003 Bytes
/
Copy pathDisappearedNumbers.java
File metadata and controls
31 lines (26 loc) · 1003 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// Time Complexity : O(n)
// Space Complexity : O(1)
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : No
class Solution {
public List<Integer> findDisappearedNumbers(int[] nums) {
List<Integer> res = new ArrayList<Integer>();
// null check
if (nums == null || nums.length == 0) return res;
/* TEMPORARY STAGE CHANGE PATTERN */
// mark all the indices for which value is encountered
for (int i = 0; i < nums.length; i++) {
int idx = Math.abs(nums[i])-1;
if (nums[idx] > 0) // if not already visited
nums[idx] *= -1; // mark visited
}
// unmark visited elements & add the unvisited elements in the result
for (int i = 0; i < nums.length; i++) {
if (nums[i] < 0)
nums[i] *= -1;
else
res.add(i+1);
}
return res;
}
}