Domanda di colloquio di Microsoft

Find two smallest elements in an unsorted array using only one pass i.e. O(n)

Risposte di colloquio

Anonimo

27 ott 2015

Initialize two variables which will the first and second elements in the array respectively. As you loop, if current value is less than both then update both, if it's between the two then only update second.

1

Anonimo

31 ott 2015

Here is my python code solution def TwoSmallest(lst): tmp_list = [lst[0],lst[1]] for i in xrange(2,len(lst)): maxi=max(tmp_list[0],tmp_list[1]) if lst[i] < maxi : tmp_list.remove(maxi) tmp_list.append(lst[i]) return tmp_list

Anonimo

12 giu 2016

If currVal < smallest, 2ndSmallest = smallest and smallest = currVal else if currVal < 2ndSmallest, 2ndSmallest = currVal