📌  相关文章
📜  通过从随机索引反转子数组形成的排序数组中的第 K 个最小元素

📅  最后修改于: 2021-09-03 03:58:13             🧑  作者: Mango

给定一个大小为N的排序数组 arr[]和一个整数K ,任务是找到数组中存在的第 K 个最小元素。给定的阵列已经通过反转子阵列获得{ARR [0],ARR [R]}{ARR [R + 1],ARR [N – 1]}在一些随机指数R.如果该不存在于数组,打印-1

例子:

朴素的方法:解决问题最简单的方法是将给定的数组arr[]按升序排序并打印数组中第K个最小的元素。

时间复杂度: O(N*log(N))
辅助空间: O(1)

高效的方法:最优的想法是基于观察到第R 个元素是最小的元素,因为[1, R]范围内的元素是颠倒的。现在,如果随机索引为R ,则表示子数组[1, R][R + 1, N]按降序排序。因此,任务减少到找到可以使用二分搜索获得的 R 的值。最后,打印第K最小元素。

请按照以下步骤解决问题:

  • l初始化为1 ,将h初始化为N,以存储二分搜索的搜索空间的边界元素索引。
  • 循环而l+1 < h 的值
    • 将中间元素存储在一个变量中, mid(l+h)/2
    • 如果arr[l] ≥ arr[mid]。如果这是真的,然后通过更新l中期检查中旬的右侧。
    • 否则,将r更新为mid
  • 现在在找到R 之后,如果K ≤ R ,那么答案是arr[R-K+1]。否则, arr[N-(KR)+1]

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to find the Kth element in a
// sorted and rotated array at random point
int findkthElement(vector arr, int n, int K)
{
     
    // Set the boundaries for binary search
    int l = 0;
    int h = n - 1, r;
 
    // Apply binary search to find R
    while (l + 1 < h)
    {
         
        // Initialize the middle element
        int mid = (l + h) / 2;
         
        // Check in the right side of mid
        if (arr[l] >= arr[mid])
            l = mid;
             
        // Else check in the left side
        else
            h = mid;
    }
     
    // Random point either l or h
    if (arr[l] < arr[h])
        r = l;
    else
        r = h;
     
    // Return the kth smallest element
    if (K <= r + 1)
        return arr[r + 1 - K];
    else
        return arr[n - (K - (r + 1))];
}
 
// Driver Code
int main()
{
     
    // Given Input
    vector arr = { 10, 8, 6, 5, 2, 1, 13, 12 };
    int n = arr.size();
    int K = 3;
     
    // Function Call
    cout << findkthElement(arr, n, K);
}
 
// This code is contributed by mohit kumar 29


Python3
# Python program for the above approach
 
# Function to find the Kth element in a
# sorted and rotated array at random point
def findkthElement(arr, n, K):
   
      # Set the boundaries for binary search
    l = 0
    h = n-1
 
    # Apply binary search to find R
    while l+1 < h:
       
          # Initialize the middle element
        mid = (l+h)//2
 
        # Check in the right side of mid
        if arr[l] >= arr[mid]:
            l = mid
 
        # Else check in the left side
        else:
            h = mid
 
    # Random point either l or h
    if arr[l] < arr[h]:
        r = l
    else:
        r = h
 
    # Return the kth smallest element
    if K <= r+1:
        return arr[r+1-K]
    else:
        return arr[n-(K-(r+1))]
 
 
# Driver Code
if __name__ == "__main__":
   
      # Given Input
    arr = [10, 8, 6, 5, 2, 1, 13, 12]
    n = len(arr)
    K = 3
     
    # Function Call
    print(findkthElement(arr, n, K) )


输出:
5

时间复杂度: O(log(N))
辅助空间: O(1)

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live