This approach uses the properties of the array and its indices to track missing numbers. By iterating through the array and using the values to mark the corresponding indices, we can identify which indices were never marked and thus determine the missing numbers.
Steps:
nums
.Time Complexity: O(n) - where n is the number of elements in the array because we are iterating over the array twice.
Space Complexity: O(1) - as no additional data structure is used apart from the output list and input array is modified in-place.
1import java.util.ArrayList;
2import java.util.List;
3
4class Solution {
5 public List<Integer> findDisappearedNumbers(int[] nums) {
6 for (int i = 0; i < nums.length; i++) {
7 int index = Math.abs(nums[i]) - 1;
8 if (nums[index] > 0) {
9 nums[index] = -nums[index];
10 }
11 }
12 List<Integer> result = new ArrayList<>();
13 for (int i = 0; i < nums.length; i++) {
14 if (nums[i] > 0) {
15 result.add(i + 1);
16 }
17 }
18 return result;
19 }
20}
In Java, arrays are used in a mutable way to modify elements by negating them to mark presence. This helps in finding missing numbers by checking which indices have positive values in the second traversal.
In this approach, we utilize a set to only store unique numbers from 1 to n that appear in the input array. By comparing this set to the complete range of numbers, we can directly determine those not present in the input.
Steps:
nums
.Time Complexity: O(n)
Space Complexity: O(n), due to use of additional boolean array to track presence of numbers.
1#include <vector>
2#include <unordered_set>
3using namespace std;
4
5vector<int> findDisappearedNumbers(vector<int>& nums) {
6 unordered_set<int> numSet(nums.begin(), nums.end());
7 vector<int> result;
8 for (int i = 1; i <= nums.size(); i++) {
9 if (numSet.find(i) == numSet.end()) {
10 result.push_back(i);
11 }
12 }
13 return result;
14}
This C++ solution utilizes an unordered_set
to track numbers appearing in the list and compares it with the complete range of potential values to find missing elements.