an interesting little algorithm

Problem Description:

    Given an array with N capacity, which store N integers from 1 to N-1 with one and only one integer

    occurs twice, please find that repeated integer. Note, limit the time complexity to O(n).

 

Solution:

int find(int a[], int N)

{

    int i, sum, base_sum;

 

    sum = 0;        // the sum of those N integers.

    for (i = 0; i < N; i++) {

        sum += a[i];

    }

    base_sum = (N*(N-1))/2;      // the sum of all the subscripts.

    return(sum - base_sum);

}

posted on 2009-11-03 22:12  John Waken  阅读(218)  评论(0编辑  收藏  举报

导航