📌  相关文章
📜  在给定的正方形中找到恰好位于 K 内的点

📅  最后修改于: 2021-10-23 08:56:03             🧑  作者: Mango

给定一个整数K和一个数组arr,其中每个元素x表示一个正方形,其两个顶点为(0, 0)(x, x) 。任务是找到恰好位于K 个方格中的点。
例子:

方法:由于所有正方形都有一个共同的角点 (0, 0),因此位于任何正方形中的任何点也将位于任何更大的正方形中。因此,我们可以简单地打印第 K 个最大正方形的另一个角。
下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
 
int PointInKSquares(int n, int a[], int k)
{
    sort(a, a + n);
    return a[n - k];
}
 
// Driver Program to test above function
int main()
{
    int k = 2;
    int a[] = { 1, 2, 3, 4 };
    int n = sizeof(a) / sizeof(a[0]);
 
    int x = PointInKSquares(n, a, k);
    cout << "(" << x << ", " << x << ")";
}


Java
// Java implementation of the approach
 
import java.io.*;
import java.util.*;
class GFG {
 
 
static int PointInKSquares(int n, int a[], int k)
{
    Arrays.sort(a);
    return a[n - k];
}
 
// Driver Program to test above function
 
    public static void main (String[] args) {
            int k = 2;
    int []a = { 1, 2, 3, 4 };
    int n = a.length;
 
    int x = PointInKSquares(n, a, k);
    System.out.println( "(" + x + ", " + x +")");
 
     
    }
}
// This code is contributed by anuj_67..


Python3
# Python 3 implementation of the
# above approach
def PointInKSquares(n, a, k) :
     
    a.sort()
    return a[n - k]
 
# Driver Code
if __name__ == "__main__" :
     
    k = 2
    a = [1, 2, 3, 4]
    n = len(a)
     
    x = PointInKSquares(n, a, k)
    print("(", x, ",", x, ")")
 
# This code is contributed by Ryuga


C#
// C# implementation of the approach
using System;
class GFG
{
 
static int PointInKSquares(int n,
                           int []a, int k)
{
    Array.Sort(a);
    return a[n - k];
}
 
// Driver Code
public static void Main (String[] args)
{
    int k = 2;
    int []a = { 1, 2, 3, 4 };
    int n = a.Length;
     
    int x = PointInKSquares(n, a, k);
    Console.WriteLine("(" + x + ", " + x +")");
}
}
 
// This code is contributed
// by Arnab Kundu


PHP


Javascript


输出:
(3, 3)