my interview question need return length of array removed duplicates can leave @ 2 duplicates.
for example, [1, 1, 1, 2, 2, 3] new array [1, 1, 2, 2, 3]. new length 5. came algorithm o(2n) believe. how can improve fastest.
def removeduplicates(nums): if nums none: return 0 if len(nums) == 0: return 0 if len(nums) == 1: return 1 new_array = {} num in nums: new_array[num] = new_array.get(num, 0) + 1 new_length = 0 key in new_array: if new_array[key] > 2: new_length = new_length + 2 else: new_length = new_length + new_array[key] return new_length new_length = removeduplicates([1, 1, 1, 2, 2, 3]) assert new_length == 5 my first question algorithm correct?
your logic correct simpler method reach goal had mentioned in question.
here logic.
myl = [1, 1, 1, 2, 2, 3, 1, 1, 1, 2, 2, 3, 1, 1, 1, 2, 2, 3] newl = [] in myl: if newl.count(i) != 2: newl.append(i) print newl [1, 1, 2, 2, 3, 3] hope helps.
Comments
Post a Comment