#include <stdio.h>#define N 10int main(){ int a[N-1]={3,9,4,5,2,6,1,8,10}, missing=0; for(int i=1; i<=N-1; i++){missing+=i-a[i-1]; }missing+=N; printf("Missing Number: %d\n", missing); return 0;}
If one number is lost:
1) subtract the sum of the current input data with 1 + 2 +... + N. Time Complexity: O (n) space complexity: O (1) [easily overflows]
2) use 12... * N divided by the total product of the current input data. Time Complexity: O (n) space complexity: O (1) [easily overflows]
3) The result of 1 ^ 2 ^... ^ N is exclusive one by one or the current input data. Time Complexity: O (n) space complexity: O (1)
4) sort the input data and traverse it from start to end. Time complexity O (nlogn) space complexity O (1)
5) hash the input data and traverse it from start to end. Time complexity O (n) space complexity O (N)
#include <iostream>using namespace std;void main(){int N=10;int num[]={1,10,4,5,6,2,8,9,3};int k=0; for(int i=1; i<N; i++) {k ^= i^num[i-1]; }printf("%d\n", k^N);}
If two numbers are lost, the hash table occupies a large space...
#include <stdio.h>#include <string.h>#define N 10#define MISSNUM 2int main(){ int a[N-MISSNUM]={3,9,5,2,6,1,8,10};int flag[N]; memset(flag, 0, sizeof(flag)); for(int i=0; i<=N-MISSNUM-1; i++){flag[a[i]-1]=1; }for(int i=0; i<=N-1; i++) {if(flag[i]==0){printf("Missing Number: %d\n", i+1); }}return 0;}