[Interview question] Which number between 1 and N is missing in an array a [n-1?

Source: Internet
Author: User
#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;}

 

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.