Wednesday, 7 January 2015

Find the unique number that is present only once in array while all the others are present three times.

Example: 2,3,5,1,2,2,5,3,5,3
Answer : 1 as 2,3,5 are repeated three times Complexity should be better than O(nlogn)

#include <stdio.h> int dnr(int arr[],int n) { int i,j,count=0,result=0; int bit=1; for (i=0;i<32;i++) { count=0; for (j=0;j<n;j++ ) { if(arr[j] & bit) count++; } count%=3; if(count) result=result | bit; bit=bit<<1; } return result; } void main() { int a[]={17,14,11,14,17,21,17,21,21,14}; printf("%d\n",dnr(a,10)); }

No comments:

Post a Comment