📌  相关文章
📜  通过用绝对差重复替换最多 2 个元素来获得数组值

📅  最后修改于: 2021-10-28 02:10:07             🧑  作者: Mango

给定一个数组arr大小N ,任务是打印数组中剩余的最终数组值,当数组的最大和第二个最大元素被替换为它们在数组中的绝对差时,重复。

注意:如果最大两个元素相同,则将两者从数组中删除,而不替换任何值。

例子:

高效方法:使用优先队列

  • 制作一个优先队列(二进制最大堆),它会自动按排序顺序排列元素。
  • 然后选择第一个元素(最大)和第二个元素(第二个最大),如果两者相等则不推送任何内容,如果不相等则推送队列中两者的绝对差异。
  • 执行上述步骤直到队列大小等于 1,然后返回最后一个元素。如果队列在达到大小 1 之前变空,则返回 0。

下面是上述方法的实现:

C
// C++ program to find the array value
// by repeatedly replacing max 2 elements
// with their absolute difference
 
#include 
using namespace std;
 
// function that return last
// value of array
int lastElement(vector& arr)
{
    // Build a binary max_heap.
    priority_queue pq;
    for (int i = 0; i < arr.size(); i++) {
        pq.push(arr[i]);
    }
 
    // For max 2 elements
    int m1, m2;
 
    // Iterate until queue is not empty
    while (!pq.empty()) {
 
        // if only 1 element is left
        if (pq.size() == 1)
 
// return the last
// remaining value
            return pq.top();
 
        m1 = pq.top();
        pq.pop();
        m2 = pq.top();
        pq.pop();
 
        // check that difference
        // is non zero
        if (m1 != m2)
            pq.push(m1 - m2);
    }
 
    // finally return 0
    return 0;
}
 
// Driver Code
int main()
{
    vector arr = { 2, 7, 4, 1, 8, 1, 1 };
 
    cout << lastElement(arr) << endl;
    return 0;
}


Java
// Java program to find the array value
// by repeatedly replacing max 2 elements
// with their absolute difference
import java.util.*;
 
class GFG{
     
// Function that return last
// value of array
static int lastElement(int[] arr)
{
     
    // Build a binary max_heap
    PriorityQueue pq = new PriorityQueue<>(
                                (a, b) -> b - a);
     
    for(int i = 0; i < arr.length; i++)
        pq.add(arr[i]);
     
    // For max 2 elements
    int m1, m2;
     
    // Iterate until queue is not empty
    while(!pq.isEmpty())
    {
         
        // If only 1 element is left
        if (pq.size() == 1)
        {
             
            // Return the last
            // remaining value
            return pq.poll();
        }
         
        m1 = pq.poll();
        m2 = pq.poll();
         
        // Check that difference
        // is non zero
        if (m1 != m2)
            pq.add(m1 - m2);
    }
     
    // Finally return 0
    return 0;
}
 
// Driver code
public static void main(String[] args)
{
    int[] arr = new int[]{2, 7, 4, 1, 8, 1, 1 };
     
    System.out.println(lastElement(arr));
}
}
 
// This code is contributed by dadi madhav


Python3
# Python3 program to find the array value
# by repeatedly replacing max 2 elements
# with their absolute difference
from queue import PriorityQueue
 
# Function that return last
# value of array
def lastElement(arr):
     
    # Build a binary max_heap.
    pq = PriorityQueue()
    for i in range(len(arr)):
         
        # Multipying by -1 for
        # max heap
        pq.put(-1 * arr[i])
     
    # For max 2 elements
    m1 = 0
    m2 = 0
     
    # Iterate until queue is not empty
    while not pq.empty():
     
        # If only 1 element is left
        if pq.qsize() == 1:
             
            # Return the last
            # remaining value
            return -1 * pq.get()
        else:
            m1 = -1 * pq.get()
            m2 = -1 * pq.get()
             
        # Check that difference
        # is non zero
        if m1 != m2 :
            pq.put(-1 * abs(m1 - m2))
             
    return 0
     
# Driver Code
arr = [ 2, 7, 4, 1, 8, 1, 1 ]
 
print(lastElement(arr))
 
# This code is contributed by ishayadav181


C#
// C# program to find the array value
// by repeatedly replacing max 2 elements
// with their absolute difference
using System;
using System.Collections.Generic;
  
class GFG{
  
// Function that return last
// value of array
static int lastElement(int[] arr)
{
     
    // Build a binary max_heap
    Queue pq = new Queue();
      
    for(int i = 0; i < arr.Length; i++)
        pq.Enqueue(arr[i]);
      
    // For max 2 elements
    int m1, m2;
      
    // Iterate until queue is not empty
    while (pq.Contains(0))
    {
         
        // If only 1 element is left
        if (pq.Count == 1)
        {
             
            // Return the last
            // remaining value
            return pq.Peek();
        }
          
        m1 = pq.Dequeue();
        m2 = pq.Peek();
          
        // Check that difference
        // is non zero
        if (m1 != m2)
            pq.Enqueue(m1 - m2);
    }
     
    // Finally return 0
    return 0;
}
  
// Driver Code
public static void Main(String[] args)
{
    int[] arr = { 2, 7, 4, 1, 8, 1, 1 };
      
    Console.WriteLine(lastElement(arr));
}
}
 
// This code is contributed by sanjoy_62


Javascript


输出:
0

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

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程