During the moment I was solving this code exercise. I couldn't figure out if my current solution is still on O(n) runtime.
Below I present my solution.
Find All Numbers Disappeared in an Array
Give an array of integers where 1 <= a[i] <= n (n = size of array), some elements appear twice and others appear once.
Find all the elements of [1, n] inclusive that do not appear in this array
Could you do it without extra space and in O(n) runtime?
Example:
Input: [4, 3, 2, 7, 8, 2, 3, 1]
Output: [5, 6]
public static void main(String[] args) {
findAllNumbersDisappeared(new int[] { 4,3,2,7,8,2,3,1});
}
/* the idea is that since we have a size _n_ array and it has numbers from 1 to n,
* given that are repeated numbers, we can iterate over the array and
* keep placing the elements in the position equal to their value
* (i.e. 1 is placed in the first position, 2 in the second, 3 in the third, and so on)
* Once that is done by swapping the elements, we iterate over the array again and
* compare the position with the value at that position.
*
* For the positions where they don't match,
* it means that whereas it should ideally have had the same value at that position (if there were no repeats),
* that positional value represents the missing number.
* */
public static void findAllNumbersDisappeared(int[] arr) {
for (int i = 0; i < arr.length; i++) {
while (arr[i] != (i+1) && arr[i] != arr[arr[i]-1]) {
swap(arr, i, arr[i]-1);
}
}
for (int i = 0; i < arr.length; i++) {
if (arr[i] != (i+1)) {
System.out.println(i+1);
}
}
}
private static void swap(int[] arr, int i, int j) {
int t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
Probably I'm confused on Big O theory. The first loop is iterated on N items (where N is the length of the array, so this is O(n)), the inner while is not executed more than N times on the whole program flow.
I don't consider this program is O(n^2), I think is between O(n) and O(n log n). Can you support me to determine the right time complexity for this solution?
Your solution is O(N), but I don't think it is correct. (Test it!)
Hint: there is a O(N) algorithm that genuinely solves the problem.
(These hints are designed to get you thinking in the right direction. I think you may already be mostly there, but I want you to get to the right solution for yourself. To maximize the learning / self-confidence-building.)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.