-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfindAllNumbersDisappearedInAnArray.ts
More file actions
63 lines (48 loc) · 1.53 KB
/
Copy pathfindAllNumbersDisappearedInAnArray.ts
File metadata and controls
63 lines (48 loc) · 1.53 KB
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/*
Given an array nums of n integers where nums[i] is in the range [1, n], return an array of all the integers in the range [1, n] that do not appear in nums.
Example 1:
Input: nums = [4,3,2,7,8,2,3,1]
Output: [5,6]
Example 2:
Input: nums = [1,1]
Output: [2]
Constraints:
n == nums.length
1 <= n <= 10^5
1 <= nums[i] <= n
Follow up: Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.
*/
function findDisappearedNumbers(nums: number[]): number[] {
const length = nums.length;
const numberCount = new Array(length + 1).fill(0);
for (let index = 0; index < length; index++) {
numberCount[nums[index]]++;
}
const missingNumber = [];
for (let index = 1; index <= length; index++) {
if (numberCount[index] === 0) {
missingNumber.push(index);
}
}
return missingNumber;
}
/*
We will use the input array as a marker
With each nums, we will negate nums[index - 1] to mark it seen,
then collect the indices where the values are still positive
*/
function findDisappearedNumbersV2(nums: number[]): number[] {
for (const num of nums) {
const index = Math.abs(num) - 1;
nums[index] = -Math.abs(nums[index]);
}
const missingNumbers = [];
for (let index = 0; index < nums.length; index++) {
if (nums[index] > 0) {
missingNumbers.push(index + 1);
}
}
return missingNumbers;
}
console.log(findDisappearedNumbersV2([4, 3, 2, 7, 8, 2, 3, 1])); // [5,6]
console.log(findDisappearedNumbersV2([1, 1])); // [2]