How to find the Kth smallest integer in an unsorted read only array?

前端 未结 3 899
你的背包
你的背包 2021-01-31 11:47

This is a standard question which has been answered many a times in several sites but in this version there are additional constraints:

  1. The array is read only (we
3条回答
  •  面向向阳花
    2021-01-31 12:08

    I've seen this problem on InterviewBit and I guess I've the solution right, captured the logic I followed to find the 'k'th smallest element in array below..

    • Find the smallest element in the array, this is the last smallest.
    • In a loop, for 'k' times, find the element that is next biggest to the smallest found in the last iteration of the loop(the last smallest found in first step will be used in the first iteration of the loop)
    • Return the last found next biggest element from the loop Copied the code below..

    int getSmallest(const int* A, int nSize){ int nSmallestElemIndex = -1; int i; for(i=0; i < nSize; i++){ if (-1 == nSmallestElemIndex){ nSmallestElemIndex = i; continue; } if (A[i] < A[nSmallestElemIndex]){ nSmallestElemIndex = i; } } return nSmallestElemIndex; } int nextBig(const int* A, int nSize, int nCurrentSmallest){ int nNextBig = -1; int i; for(i=0; i < nSize; i++){ if (i == nCurrentSmallest || A[i] < A[nCurrentSmallest]){ continue; } if (A[i] == A[nCurrentSmallest] && i <= nCurrentSmallest){ continue; } if (nNextBig == -1){ nNextBig = i; continue; } if (A[i] >= A[nCurrentSmallest] && A[i] < A[nNextBig]){ nNextBig = i; } } return nNextBig; } int kthsmallest(const int* A, int n1, int B) { int nSmallestElem = getSmallest(A, n1); int nCount = 1; int nRes = nSmallestElem; while(nCount < B){ nRes = nextBig(A, n1, nRes); nCount++; } return nRes; }

    I executed and validated it for the test cases on my machine but it's not accepted at Interviewbit.

    I'll be glad if the solution passes your validation. Let me know your comments.

提交回复
热议问题