2013年3月14日 星期四

Find duplicated numbers in an array.

Question:
Given an array with N+M items, each item is number between 1 to N, please give a O(M+N) solution to print all duplicated numbers.

Answer:
#include "stdafx.h"
#include 

using namespace std;

void printDuplicate(int arr[], int nm, int n);

int _tmain(int argc, _TCHAR* argv[])
{
    const int n = 10, m = 5;
    const int nm = n+m;
    int arr[nm] = {1,2,3,4,5,6,7,8,9,10,1,2,3,4,2};

    printDuplicate(arr, nm, n);

    std::cin.get();
    return 0;
}

void printDuplicate(int arr[], int nm, int n)
{
    int* pArray = new int[n];
    for (int i=0; i<n; i++)
    {
        pArray[i] = 0;
    }

    for (int i=0; i<nm; i++)
    {
        int value = arr[i];
        pArray[value]++;

        if (pArray[value] == 2)
            cout << value << endl;
    }
}


Advanced Question:
Give an answer without using extra space.

Answer:
Change function printDumplicate as below.
void printDuplicate(int arr[], int nm, int n)
{
    int pArray = 0;

    for (int i=0; i 0)
            cout << value << endl;

        pArray |= (1 << (value-1));
    }
}


Thinking:
If you use bits of an integer variable to keep all status, remember that there are 32 bits only.


* All answer just my answer, not the best one.

沒有留言:

張貼留言