Algorithm: efficient way to remove duplicate integers from an array

前端 未结 30 2734
离开以前
离开以前 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:17

    You could do this in a single traversal, if you are willing to sacrifice memory. You can simply tally whether you have seen an integer or not in a hash/associative array. If you have already seen a number, remove it as you go, or better yet, move numbers you have not seen into a new array, avoiding any shifting in the original array.

    In Perl:

    foreach $i (@myary) {
        if(!defined $seen{$i}) {
            $seen{$i} = 1;
            push @newary, $i;
        }
    }
    

提交回复
热议问题