Back to course home
0% completed
Vote For New Content
Alternative Solution
Shane
Jul 14, 2023
- place all numbers at the correct index
- store the wrongly indexed numbers in an object while reducing k
- if k is greater than 0 add the remaining numbers to the missing array. to do this, you need to ensure its not in the store object which has all the numbers that already exist in the initial array that were wrongly indexed.
class Solution { findNumbers(nums, k) { let missingNumbers = []; let n = nums.length; let store = {} for (let i = 0; i < n; i++) { if (nums[i] > 0 && nums[i] <= n && nums[i] !== nums[nums[i] - 1]) { [nums[nums[i] - 1], nums[i]] = [nums[i], nums[nums[i] - 1]]; i-- } } for (let i = 0; i < n; i++) { if (nums[i] !== i + 1 && k != 0){ store[nums[i]] = 1 missingNumbers.push(i+1) k-=1 } } while(k > 0){ if(!!store[n+1]){ n++ continue } missingNumbers.push(++n) k-=1 } return missingNumbers } }
0
0
Comments
Comments
On this page