algorithm - Given an array of 2n elements of which n are similar and n are different -
algorithm - Given an array of 2n elements of which n are similar and n are different -
given array of 2n elements of n elements same , remaining n elements different. write c programme find out value nowadays n times in array
i thought in next way- compare a[i] , a[i+1] , compare a[i] , a[i+2] , homecoming element
this run in o(n) time..can give improve solution?
i going through solutions saying this-
declare 2 variables a) count variable maintain track of count of bulk element. majority element. do loop , repeat next steps 4-6 until end of array reached. if current array element equals bulk element, increment count else, if count 0, update bulk element current array element , increment count. else if count not 0 decrement count. do loop , count number of occurrences of bulk element in array, if it's half array size have found bulk element, else there's no bulk element.
you can utilize bulk element algorithm basis o(n) solution o(1) space.
you need space 1 stored element. pick first element , store it, if next element same stored one, finished. if not, restart algorithm next step. if don't find element after end of this, means element ordered in pairs (a,b),(a,c),(a,d) or (b,a),(a,c),(a,d),(e,a).. compare first 4 elements , have found duplicate.
since elements can in arbitrary order, whichever first n/2 elements check it's possible different. there no solution bettern o(n).
algorithm
Comments
Post a Comment