algorithm - Way to judge if two Arrays are identical? -
by identical
mean 2 arrays contain same elements, order of elements in arrays not matter here.
the solution came this(which turns out wrong approach pointed out in comments):
if size of 2 arrays equal see true, find elements of array in array b found, find elements of array b in array found, conclusion 2 arrays identical
however, there better algorithm in term of time complexity?
let's have user[]
array 1 , user[]
array 2. can lop through array 1 , add them dictionary<user, int>
dictionary key user , value count. loop through second array , each user in array 2 decrement count in dictionary (if count greater 1) or remove element (if count 1). if user isn't in dictionary, can stop, arrays don't match.
if end , had checked length of arrays same, arrays match. if hadn't checked length earlier (which of course still should have), can verify dictionary empty after looping through array 2.
i don't know performance of is, faster sorting both lists , looping through them comparing element element. takes more memory though, if arrays not super large memory usage shouldn't issue.
Comments
Post a Comment