Question d’entretien chez Amazon

In Array find largest second number ?

Réponses aux questions d'entretien

Utilisateur anonyme

21 juin 2016

Can,t we do sorting from largest to smallest give arr[1] which is of course second largest

2

Utilisateur anonyme

14 févr. 2016

It Took Time but Simple logic is needed.

1

Utilisateur anonyme

23 févr. 2016

Would be impressive to solve the general case... find the kth large number: create a minheap of size k, and for each element in the array, if that number is bigger than the top of the minheap, replace the top of the minheap with that number and recreate the minheap. Running time is O(nlgn). If you can have negative numbers, then you can easily modify this code. int findKthLargestNumber(int[] A, int k) { if (k minHeap[2*i+1]) { int temp = minHeap[i]; minHeap[i] = minHeap[2*i+1]; minHeap[ 2*i+1] = temp; i = 2*i+1; } else if (minHeap.length minHeap[2*i+2)]) { int temp = minHeap[i]; minHeap[i] = minHeap[2*i+2]; minHeap[ 2*i+2] = temp; i = 2*i+2; } else { done = true; } }

Utilisateur anonyme

28 févr. 2016

Since it asks for the second largest number, you can define two variables: theLargest theSecondLargest And scan the array and update these two variables accordingly. If it extends to find the Kth number and K is not very large (e.g. 1000), you can use a minHeap with size K. If the value of K can be very large, you can talk with the interviewer the pros and cons of these two methods: 1) MInHeap 2) QuickSelect