Frage im Vorstellungsgespräch bei Microsoft

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

Antworten zu Vorstellungsgespräch

Anonym

27. Okt. 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

Anonym

31. Okt. 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

Anonym

12. Juni 2016

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