Pregunta de entrevista de Amazon

In Array find largest second number ?

Respuestas de entrevistas

Anónimo

21 jun 2016

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

2

Anónimo

14 feb 2016

It Took Time but Simple logic is needed.

1

Anónimo

23 feb 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; } }

Anónimo

28 feb 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