查找给定数组的加权中位数的程序

发布于 2024-06-18 01:25:55 字数 12706 浏览 35 评论 0

给定两个包含 N 个整数的数组 arr[] 和包含 N 个 权重的 W[] ,其中 W[i] 是元素 arr[i] 的权重。任务是找到给定数组的加权中位数。

注意:所有元素的权重总和始终为 1。

Let the array arr[] be arranged in increasing order with their corresponding weights.

If N is odd, then there is only one weighted median say arr[k] which satisfies the below property:

$$\sum _{i=1}^{k-1}W_{i}\leq 1/2 \;and\; \sum _{i=k+1}^{N}W_{i}\leq 1/2$$

If N is even, then there are two weighted medians, i.e., lower and upper weighted median.

The lower weighted median for element arr[k] which satisfies the following:

$$\sum _{i=1}^{k-1}W_{i}< 1/2 \;and\; \sum _{i=k+1}^{N}W_{i}= 1/2$$

The upper weighted median for element arr[k] which satisfies the following:

$$\sum _{i=1}^{k-1}W_{i}= 1/2 \;and\; \sum _{i=k+1}^{N}W_{i}< 1/2$$

例子:

Input: arr={5, 1, 3, 2, 4}, W=[0.25, 0.15, 0.2, 0.1, 0.3]
Output: The weighted median is element 4
Explanation:
Here the number of element is odd, so there is only one weighted median because at K = 3 the above condition is satisfied.
The cumulative weights on each side of element 4 is 0.45 and 0.25.

Input: arr=[4, 1, 3, 2], W=[0.25, 0.49, 0.25, 0.01]
Output:
The lower weighted median is element 2
The upper weighted median is element 3
Explanation:
Here there are an even number of elements, so there are two weighted medians.
Lower weighted median is at K = 2 because at K = 2 the above condition is satisfied with cumulative weight on each side of element 2 is 0.49 and 0.5.
Upper weighted median is at K = 3 because at K = 3 the above condition is satisfied with cumulative weight on each side of element 3 is 0.5 and 0.25.

方法:按照以下步骤解决给定的问题:

  1. 现在要以递增的顺序查找数组arr[]的中位数,它们各自的权重顺序不应改变。
  2. 因此,创建一组对,其中该对的第一个元素将是arr[i] ,该对的第二个元素将是其相应的权重W[i]
  3. 然后根据arr[]值对 Pairs 集进行排序。
  4. 如果对数为奇数,则求加权中位数为:
    • 遍历对集并通过添加权重计算总和。
    • 当总和大于 0.5 时,打印该对的arr[i]值。
  5. 但是,如果对的数量是偶数,则找到下加权中位数和上加权中位数:
    • 对于较低的中位数,从左侧遍历集合对并通过添加权重来计算总和。
    • 当总和大于或等于 0.5 时,打印该对的arr[i]值。
    • 对于上中位数,从右侧遍历集合对并通过添加权重计算总和。
    • 当总和大于或等于 0.5 时,打印该对的arr[i]值。

下面是上述方法的实现:

C++14

// C++ program for the above approach
#include 
using namespace std;
 
// Function to calculate weighted median
void weightedMedian(vector arr,
                    vector W)
{
     
    // Store pr of arr[i] and W[i]
    vector<pair<int, float="">> pr;
 
    for(int index = 0;
            index < arr.size();
            index++)
        pr.push_back({arr[index],
                        W[index]});
 
    // Sort the list of pr w.r.t.
    // to their arr[] values
    sort(pr.begin(), pr.end());
     
    // If N is odd
    if (arr.size() % 2 != 0)
    {
         
        // Traverse the set pr
        // from left to right
        float sums = 0;
        for(auto element : pr)
        {
             
            // Update sums
            sums += element.second;
 
            // If sum becomes > 0.5
            if (sums > 0.5)
                cout << "The Weighted Median is element "
                     << element.first << endl;
        }
    }
       
    // If N is even
    else
    {
         
        // For lower median traverse
        // the set pr from left
        float sums = 0;
        for(auto element : pr)
        {
             
            // Update sums
            sums += element.second;
 
            // When sum >= 0.5
            if (sums >= 0.5)
            {
                cout << "Lower Weighted Median is element "
                     << element.first << endl;
                break;
            }
        }
         
        // For upper median traverse
        // the set pr from right
        sums = 0;
        for(int index = pr.size() - 1;
                index >= 0;
                index--)
        {
            int element = pr[index].first;
            float weight = pr[index].second;
 
            // Update sums
            sums += weight;
 
            // When sum >= 0.5
            if (sums >= 0.5)
            {
                cout << "Upper Weighted Median is element "
                     << element;
                break;
            }
        }
    }
}
 
// Driver Code
int main()
{
     
    // Given array arr[]
    vector arr = { 4, 1, 3, 2 };
     
    // Given weights W[]
    vector W = { 0.25, 0.49, 0.25, 0.01 };
     
    // Function Call
    weightedMedian(arr, W);
}
 
// This code is contributed by mohit kumar 29</pair<int,>

Java

// Java program for the
// above approach
import java.util.*;
class GFG{
 
static class Pair implements Comparable
{
  int first;
  double second;
 
  Pair(int f, double s)
  {
    first = f;
    second = s;
  }
 
  @Override
  public int compareTo(Pair o)
  {
    if(this.second > o.second)
      return 1;
    else if(this.second == o.second)
      return 0;
    return -1;
  }
}
 
// Function to calculate weighted median
static void weightedMedian(Vector arr,
                           Vector W)
{
  // Store pr of arr[i] and W[i]
  Vector pr = new Vector<>();
 
  for(int index = 0;
      index < arr.size();
      index++)
    pr.add(new Pair(arr.get(index),
                    W.get(index)));
 
  // Sort the list of pr w.r.t.
  // to their arr[] values
  Collections.sort(pr);
 
  // If N is odd
  if (arr.size() % 2 != 0)
  {
    // Traverse the set pr
    // from left to right
    float sums = 0;
    for(Pair element : pr)
    {
      // Update sums
      sums += element.second;
 
      // If sum becomes > 0.5
      if (sums > 0.5)
        System.out.print(
               "The Weighted Median is element " +
                element.first + "\n");
    }
  }
 
  // If N is even
  else
  {
    // For lower median traverse
    // the set pr from left
    double sums = 0;
    for(Pair element : pr)
    {
      // Update sums
      sums += element.second;
 
      // When sum >= 0.5
      if (sums <= 0.5)
      {
        System.out.print(
               "Lower Weighted Median is element " +
                element.first + "\n");
        break;
      }
    }
 
    // For upper median traverse
    // the set pr from right
    sums = 0;
    for(int index = pr.size() - 1;
            index >= 0; index--)
    {
      int element = pr.get(index).first;
      double weight = pr.get(index).second;
 
      // Update sums
      sums += weight;
 
      // When sum >= 0.5
      if (sums >= 0.5)
      {
        System.out.print(
               "Upper Weighted Median is element " +
                element);
        break;
      }
    }
  }
}
 
// Driver Code
public static void main(String[] args)
{   
  // Given array arr[]
  Vector arr = new Vector<>();
  arr.add(4);
  arr.add(1);
  arr.add(3);
  arr.add(2);
 
  // Given weights W[]
  Vector W =   new Vector<>();
  W.add(0.25);
  W.add(0.49);
  W.add(0.25);
  W.add(0.01);
 
  // Function Call
  weightedMedian(arr, W);
}
}
 
// This code is contributed by gauravrajput1

Python3

# Python3 program for the above approach
 
# Function to calculate weighted median
def weightedMedian(arr, W):
 
    # Store pairs of arr[i] and W[i]
    pairs = []
     
    for index in range(len(arr)):
        pairs.append([arr[index], W[index]])
 
    # Sort the list of pairs w.r.t.
    # to their arr[] values
    pairs.sort(key = lambda p: p[0])
 
    # If N is odd
    if len(arr) % 2 != 0:
 
        # Traverse the set pairs
        # from left to right
        sums = 0
        for element, weight in pairs:
         
            # Update sums
            sums += weight
 
            # If sum becomes > 0.5
            if sums > 0.5:
                print("The Weighted Median", end = ' ')
                print("is element {}".format(element))
 
    # If N is even
    else:
 
        # For lower median traverse
        # the set pairs from left
        sums = 0
        for element, weight in pairs:
             
            # Update sums
            sums += weight
 
            # When sum >= 0.5
            if sums >= 0.5:
                print("Lower Weighted Median", end = ' ')
                print("is element {}".format(element))
                break
 
        # For upper median traverse
        # the set pairs from right
        sums = 0
        for index in range(len(pairs)-1, -1, -1):
         
            element = pairs[index][0]
            weight = pairs[index][1]
             
            # Update sums
            sums += weight
 
            # When sum >= 0.5
            if sums >= 0.5:
                print("Upper Weighted Median", end = ' ')
                print("is element {}".format(element))
                break
 
# Driver Code
if __name__ == "__main__":
     
    # Given array arr[]
    arr = [4, 1, 3, 2]
     
    # Given weights W[]
    W = [0.25, 0.49, 0.25, 0.01]
 
    # Function Call
    weightedMedian(arr, W)

C#

// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
     
// Function to calculate weighted median
static void weightedMedian(int[] arr,
                           float[] W)
{
     
    // Store pr of arr[i] and W[i]
    List<tuple<int,                float="">> pr = new List<tuple<int,                                            float="">>();
  
    for(int index = 0; index < arr.Length; index++)
        pr.Add(new Tuple<int, float="">(arr[index], W[index]));
  
    // Sort the list of pr w.r.t.
    // to their arr[] values
    pr.Sort();
      
    // If N is odd
    if (arr.Length % 2 != 0)
    {
         
        // Traverse the set pr
        // from left to right
        float sums = 0;
        foreach(Tuple<int, float=""> element in pr)
        {
             
            // Update sums
            sums += element.Item2;
  
            // If sum becomes > 0.5
            if (sums > 0.5)
                Console.WriteLine("The Weighted Median " +
                                  "is element " + element.Item1);
        }
    }
        
    // If N is even
    else
    {
         
        // For lower median traverse
        // the set pr from left
        float sums = 0;
        foreach(Tuple<int, float=""> element in pr)
        {
             
            // Update sums
            sums += element.Item2;
  
            // When sum >= 0.5
            if (sums >= 0.5)
            {
                Console.WriteLine("Lower Weighted Median " +
                                  "is element " + element.Item1);
                break;
            }
        }
          
        // For upper median traverse
        // the set pr from right
        sums = 0;
        for(int index = pr.Count - 1; index >= 0; index--)
        {
            int element = pr[index].Item1;
            float weight = pr[index].Item2;
  
            // Update sums
            sums += weight;
  
            // When sum >= 0.5
            if (sums >= 0.5)
            {
                Console.Write("Upper Weighted Median " + 
                              "is element " + element);
                break;
            }
        }
    }
}
 
// Driver code
static void Main()
{
     
    // Given array arr[]
    int[] arr = { 4, 1, 3, 2 };
      
    // Given weights W[]
    float[] W = { 0.25f, 0.49f, 0.25f, 0.01f };
      
    // Function Call
    weightedMedian(arr, W);
}
}
 
// This code is contributed by divyeshrabadiya07</int,></int,></int,></tuple<int,></tuple<int,>

输出:

Lower Weighted Median is element 2
Upper Weighted Median is element 3

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

关于作者

顾挽

暂无简介

0 文章
0 评论
756 人气
更多

推荐作者

謌踐踏愛綪

文章 0 评论 0

开始看清了

文章 0 评论 0

高速公鹿

文章 0 评论 0

alipaysp_PLnULTzf66

文章 0 评论 0

热情消退

文章 0 评论 0

白色月光

文章 0 评论 0

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文