📜  N 个区间中第 K 个最大的偶数

📅  最后修改于: 2022-05-13 01:56:09.077000             🧑  作者: Mango

N 个区间中第 K 个最大的偶数

给定一个有N个范围的二维数组arr[] ,表示从LR的整数区间,以及一个数字K ,任务是找到第 K 个最大的偶数。

例子

方法:给定的问题可以通过使用合并重叠区间的方法来解决。这个想法是根据范围的下限对间隔进行排序并将它们合并以消除整数的重复。然后可以按照以下步骤解决问题:

  • 如果K<=0N=0则返回 -1
  • 初始化, L = arr[ i].first 和R = arr[i].second
  • 初始化一个变量范围,存储范围内的偶数
  • 在从idx到 0 的循环中迭代
    • 如果R是奇数
      • 范围=地板((R - L + 1)/ 2)
      • 如果, K > 范围K = K – 范围
      • 否则返回R – 2 * K + 1
    • 如果R是偶数
      • 范围= ceil((float)(R – L + 1) / 2)
      • 如果, K > 范围K = K – 范围
      • 否则, R – 2 * K + 2
  • 返回 -1

下面是上述方法的实现:

C++
// C++ implementation for the above approach
#include 
#include 
using namespace std;
 
// Function to merge overlapping intervals
// and return the Kth largest even number
int calcEven(vector > V,
             int N, int k)
{
 
    // Base Case
    if (k <= 0 || N == 0)
        return -1;
 
    // Sort the intervals in increasing order
    // according to their first element
    sort(V.begin(), V.end());
 
    int i, idx = 0;
 
    // Merging the overlaping intervals
    for (i = 1; i < N; i++) {
 
        // If it overlaps with
        // the previous intervals
        if ((V[idx].second >= V[i].first)
            || (V[i].first == V[idx].second + 1)) {
 
            // Merge previous and current intervals
            V[idx].second = max(V[idx].second,
                                V[i].second);
        }
        else {
 
            // Increment the index
            idx++;
 
            V[idx].second = V[i].second;
            V[idx].first = V[i].first;
        }
    }
 
    // Find Kth largest even number
    for (i = idx; i >= 0; i--) {
 
        // Initialize L and R
        int L = V[i].first;
        int R = V[i].second;
 
        // If R is odd
        if (R & 1) {
 
            // Calculate number of even
            // numbers within the range
            int range = (R - L + 1) / 2;
 
            // if k > range then kth largest
            // even number is not in this range
            if (k > range) {
 
                k -= range;
            }
            else
                return (R - 2 * k + 1);
        }
        else {
 
            // Calculate number of even
            // numbers within the range
            int range = ceil((float)(R - L + 1) / 2);
 
            // if k > range then kth largest
            // even number is not in this range
            if (k > range) {
 
                k -= range;
            }
            else
                return (R - 2 * k + 2);
        }
    }
 
    // No Kth even number in the range
    // so return -1
    return -1;
}
 
// Driver Code
int main()
{
 
    // Initialize the ranges
    vector > vec = { { 12, 15 },
                                    { 3, 9 },
                                    { 2, 5 },
                                    { 20, 25 },
                                    { 16, 20 } };
 
    int N = vec.size();
 
    // Initialize K
    int K = 9;
 
    // Print the answer
    cout << calcEven(vec, N, K);
 
    return 0;
}


Java
// Java implementation for the above approach
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
 
class GFG {
 
  static class Pair {
    int first = 0;
    int second = 0;
 
    public Pair(int first, int second) {
      this.first = first;
      this.second = second;
    }
  }
 
  // Function to merge overlapping intervals
  // and return the Kth largest even number
  public static int calcEven(ArrayList V, int N, int k) {
 
    // Base Case
    if (k <= 0 || N == 0)
      return -1;
 
    // Sort the intervals in increasing order
    // according to their first element
    Collections.sort(V, new Comparator() {
      @Override
      public int compare(Pair p1, Pair p2) {
        return p1.first - p2.first;
      }
    });
 
    int i, idx = 0;
 
    // Merging the overlaping intervals
    for (i = 1; i < N; i++) {
 
      // If it overlaps with
      // the previous intervals
      if ((V.get(idx).second >= V.get(i).first) || (V.get(i).first == V.get(idx).second + 1)) {
 
        // Merge previous and current intervals
        V.get(idx).second = Math.max(V.get(idx).second, V.get(i).second);
      } else {
 
        // Increment the index
        idx++;
 
        V.get(idx).second = V.get(i).second;
        V.get(idx).first = V.get(i).first;
      }
    }
 
    // Find Kth largest even number
    for (i = idx; i >= 0; i--) {
 
      // Initialize L and R
      int L = V.get(i).first;
      int R = V.get(i).second;
 
      // If R is odd
      if ((R & 1) > 0) {
 
        // Calculate number of even
        // numbers within the range
        int range = (R - L + 1) / 2;
 
        // if k > range then kth largest
        // even number is not in this range
        if (k > range) {
 
          k -= range;
        } else
          return (R - 2 * k + 1);
      } else {
 
        // Calculate number of even
        // numbers within the range
        int range = (int) Math.ceil((R - L + 1) / 2);
 
        // if k > range then kth largest
        // even number is not in this range
        if (k > range) {
 
          k -= range;
        } else
          return (R - 2 * k + 2);
      }
    }
 
    // No Kth even number in the range
    // so return -1
    return -1;
  }
 
  // Driver Code
  public static void main(String args[]) {
 
    // Initialize the ranges
    ArrayList vec = new ArrayList();
 
    vec.add(new Pair(12, 15));
    vec.add(new Pair(3, 9));
    vec.add(new Pair(2, 5));
    vec.add(new Pair(20, 25));
    vec.add(new Pair(16, 20));
 
    int N = vec.size();
 
    // Initialize K
    int K = 9;
 
    // Print the answer
    System.out.println(calcEven(vec, N, K));
  }
}
 
// This code is contributed by gfgking.


Python3
# python implementation for the above approach
import math
 
# Function to merge overlapping intervals
# and return the Kth largest even number
def calcEven(V, N, k):
 
    # Base Case
    if (k <= 0 or N == 0):
        return -1
 
    # Sort the intervals in increasing order
    # according to their first element
    V.sort()
 
    idx = 0
 
    # Merging the overlaping intervals
    for i in range(1, N):
 
        # If it overlaps with
        # the previous intervals
        if ((V[idx][1] >= V[i][0]) or (V[i][0] == V[idx][1] + 1)):
 
            # Merge previous and current intervals
            V[idx][1] = max(V[idx][1], V[i][1])
 
        else:
 
           # Increment the index
            idx += 1
 
            V[idx][1] = V[i][1]
            V[idx][0] = V[i][0]
 
        # Find Kth largest even number
    for i in range(idx, -1, -1):
 
        # Initialize L and R
        L = V[i][0]
        R = V[i][1]
 
        # If R is odd
        if (R & 1):
 
            # Calculate number of even
            # numbers within the rng
            rng = (R - L + 1) // 2
 
            # if k > rng then kth largest
            # even number is not in this rng
            if (k > rng):
                k -= rng
 
            else:
                return (R - 2 * k + 1)
 
        else:
 
            # Calculate number of even
            # numbers within the rng
            rng = math.ceil((R - L + 1) / 2)
 
            # if k > rng then kth largest
            # even number is not in this rng
            if (k > rng):
                k -= rng
 
            else:
                return (R - 2 * k + 2)
 
        # No Kth even number in the rng
        # so return -1
    return -1
 
# Driver Code
if __name__ == "__main__":
 
   # Initialize the ranges
    vec = [[12, 15], [3, 9], [2, 5], [20, 25], [16, 20]]
 
    N = len(vec)
 
    # Initialize K
    K = 9
 
    # Print the answer
    print(calcEven(vec, N, K))
 
    # This code is contributed by rakeshsahni


Javascript


输出
6

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