Algorithm to determine if array contains n…n+m?

前端 未结 30 3095
清酒与你
清酒与你 2020-11-28 01:45

I saw this question on Reddit, and there were no positive solutions presented, and I thought it would be a perfect question to ask here. This was in a thread about interview

30条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-28 02:02

    Hazzen's algorithm implementation in C

    #include
    
    #define swapxor(a,i,j) a[i]^=a[j];a[j]^=a[i];a[i]^=a[j];
    
    int check_ntom(int a[], int n, int m) {
        int i = 0, j = 0;
        for(i = 0; i < m; i++) {
            if(a[i] < n || a[i] >= n+m) return 0;   //invalid entry
            j = a[i] - n;
            while(j != i) {
                if(a[i]==a[j]) return -1;           //bucket already occupied. Dupe.
                swapxor(a, i, j);                   //faster bitwise swap
                j = a[i] - n;
                if(a[i]>=n+m) return 0;             //[NEW] invalid entry
            }
        }
        return 200;                                 //OK
    }
    
    int main() {
        int n=5, m=5;
        int a[] = {6, 5, 7, 9, 8};
        int r = check_ntom(a, n, m);
        printf("%d", r);
        return 0;
    }
    

    Edit: change made to the code to eliminate illegal memory access.

提交回复
热议问题