Algorithm: efficient way to remove duplicate integers from an array

前端 未结 30 2810
离开以前
离开以前 2020-11-22 16:03

I got this problem from an interview with Microsoft.

Given an array of random integers, write an algorithm in C that removes duplicated numbers an

30条回答
  •  情书的邮戳
    2020-11-22 16:38

    First, you should create an array check[n] where n is the number of elements of the array you want to make duplicate-free and set the value of every element(of the check array) equal to 1. Using a for loop traverse the array with the duplicates, say its name is arr, and in the for-loop write this :

    {
        if (check[arr[i]] != 1) {
            arr[i] = 0;
        }
        else {
            check[arr[i]] = 0;
        }
    }
    

    With that, you set every duplicate equal to zero. So the only thing is left to do is to traverse the arr array and print everything it's not equal to zero. The order stays and it takes linear time (3*n).

提交回复
热议问题