📌  相关文章
📜  将每个元素替换为其右边最小的元素

📅  最后修改于: 2021-05-24 23:49:23             🧑  作者: Mango

给定一个整数数组,将每个元素替换为其数组右侧最小的元素。如果右侧没有更多元素,则将其替换为-1。

例子:

Input: [8, 58, 71, 18, 31, 32, 63, 92, 
         43, 3, 91, 93, 25, 80, 28]
Output: [18, 63, 80, 25, 32, 43, 80, 93, 
         80, 25, 93, -1, 28, -1, -1]

天真的方法是运行两个循环。外循环将从左到右一个接一个的拾取数组元素。内循环将找到比其右侧的拾取元素大的最小元素。最后,外循环将用内循环找到的元素替换选取的元素。该方法的时间复杂度将为O(n 2 )。

一个棘手的解决方案是使用二进制搜索树。我们开始从右到左扫描阵列,并将每个元素插入BST。对于每个插入的元素,我们在BST中用其顺序后继替换它在数组中。如果插入的元素是目前为止最大的元素(即不存在其有序后继元素),则将其替换为-1。

以下是上述想法的实现–

C++
// C++ program to replace every element with the
// least greater element on its right
#include 
using namespace std;
 
// A binary Tree node
struct Node {
    int data;
    Node *left, *right;
};
 
// A utility function to create a new BST node
Node* newNode(int item)
{
    Node* temp = new Node;
    temp->data = item;
    temp->left = temp->right = NULL;
 
    return temp;
}
 
/* A utility function to insert a new node with
   given data in BST and find its successor */
Node* insert(Node* node, int data, Node*& succ)
{
     
    /* If the tree is empty, return a new node */
    if (node == NULL)
        return node = newNode(data);
 
    // If key is smaller than root's key, go to left
    // subtree and set successor as current node
    if (data < node->data) {
        succ = node;
        node->left = insert(node->left, data, succ);
    }
 
    // go to right subtree
    else if (data > node->data)
        node->right = insert(node->right, data, succ);
    return node;
}
 
// Function to replace every element with the
// least greater element on its right
void replace(int arr[], int n)
{
    Node* root = NULL;
 
    // start from right to left
    for (int i = n - 1; i >= 0; i--) {
        Node* succ = NULL;
 
        // insert current element into BST and
        // find its inorder successor
        root = insert(root, arr[i], succ);
 
        // replace element by its inorder
        // successor in BST
        if (succ)
            arr[i] = succ->data;
        else // No inorder successor
            arr[i] = -1;
    }
}
 
// Driver Program to test above functions
int main()
{
    int arr[] = { 8,  58, 71, 18, 31, 32, 63, 92,
                  43, 3,  91, 93, 25, 80, 28 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    replace(arr, n);
 
    for (int i = 0; i < n; i++)
        cout << arr[i] << " ";
 
    return 0;
}


Java
// Java program to replace every element with
// the least greater element on its right
import java.io.*;
 
class BinarySearchTree{
     
// A binary Tree node
class Node
{
    int data;
    Node left, right;
 
    Node(int d)
    {
        data = d;
        left = right = null;
    }
}
 
// Root of BST
static Node root;
static Node succ;
 
// Constructor
BinarySearchTree()
{
    root = null;
    succ = null;
}
 
// A utility function to insert a new node with
// given data in BST and find its successor
Node insert(Node node, int data)
{
     
    // If the tree is empty, return a new node
    if (node == null)
    {
        node = new Node(data);
    }
 
    // If key is smaller than root's key,
    // go to left subtree and set successor
    // as current node
    if (data < node.data)
    {
        succ = node;
        node.left = insert(node.left, data);
    }
 
    // Go to right subtree
    else if (data > node.data)
        node.right = insert(node.right, data);
         
    return node;
}
 
// Function to replace every element with the
// least greater element on its right
static void replace(int arr[], int n)
{
    BinarySearchTree tree = new BinarySearchTree();
 
    // start from right to left
    for(int i = n - 1; i >= 0; i--)
    {
        succ = null;
         
        // Insert current element into BST and
        // find its inorder successor
        root = tree.insert(root, arr[i]);
 
        // Replace element by its inorder
        // successor in BST
        if (succ != null)
            arr[i] = succ.data;
             
        // No inorder successor
        else
            arr[i] = -1;
    }
}
 
// Driver code
public static void main(String[] args)
{
    int arr[] = new int[] { 8, 58, 71, 18, 31,
                            32, 63, 92, 43, 3,
                            91, 93, 25, 80, 28 };
    int n = arr.length;
 
    replace(arr, n);
 
    for(int i = 0; i < n; i++)
        System.out.print(arr[i] + " ");
}
}
 
// The code is contributed by Tushar Bansal


Python3
# Python3 program to replace every element
# with the least greater element on its right
 
# A binary Tree node
class Node:
     
    def __init__(self, d):
         
        self.data = d
        self.left = None
        self.right = None
 
# A utility function to insert a new node with
# given data in BST and find its successor
def insert(node, data):
     
    global succ
     
    # If the tree is empty, return a new node
    root = node
 
    if (node == None):
        return Node(data)
 
    # If key is smaller than root's key, go to left
    # subtree and set successor as current node
    if (data < node.data):
         
        #print("1")
        succ = node
        root.left = insert(node.left, data)
 
    # Go to right subtree
    elif (data > node.data):
        root.right = insert(node.right, data)
         
    return root
 
# Function to replace every element with the
# least greater element on its right
def replace(arr, n):
     
    global succ
    root = None
 
    # Start from right to left
    for i in range(n - 1, -1, -1):
        succ = None
 
        # Insert current element into BST and
        # find its inorder successor
        root = insert(root, arr[i])
 
        # Replace element by its inorder
        # successor in BST
        if (succ):
            arr[i] = succ.data
         
        # No inorder successor
        else:  
            arr[i] = -1
             
    return arr
 
# Driver code
if __name__ == '__main__':
     
    arr = [ 8, 58, 71, 18, 31, 32, 63,
            92, 43, 3, 91, 93, 25, 80, 28 ]
    n = len(arr)
    succ = None
 
    arr = replace(arr, n)
 
    print(*arr)
 
# This code is contributed by mohit kumar 29


C#
// C# program to replace every element with
// the least greater element on its right
using System;
 
class BinarySearchTree{
     
// A binary Tree node
public class Node
{
    public int data;
    public Node left, right;
     
    public Node(int d)
    {
        data = d;
        left = right = null;
    }
}
 
// Root of BST
public static Node root;
public static Node succ;
 
// Constructor
public BinarySearchTree()
{
    root = null;
    succ = null;
}
 
// A utility function to insert a new node with
// given data in BST and find its successor
public static Node insert(Node node, int data)
{
     
    // If the tree is empty, return a new node
    if (node == null)
    {
        node = new Node(data);
    }
     
    // If key is smaller than root's key,
    // go to left subtree and set successor
    // as current node
    if (data < node.data)
    {
        succ = node;
        node.left = insert(node.left, data);
    }
     
    // Go to right subtree
    else if (data > node.data)
    {
        node.right = insert(node.right, data);
    }
    return node;
}
 
// Function to replace every element with the
// least greater element on its right
public static void replace(int[] arr, int n)
{
    //BinarySearchTree tree = new BinarySearchTree();
    // Start from right to left
    for(int i = n - 1; i >= 0; i--)
    {
        succ = null;
         
        // Insert current element into BST and
        // find its inorder successor
        root = BinarySearchTree.insert(root, arr[i]);
         
        // Replace element by its inorder
        // successor in BST
        if (succ != null)
        {
            arr[i] = succ.data;
        }
         
        // No inorder successor
        else
        {
            arr[i] = -1;
        }
    }
}
 
// Driver code
static public void Main()
{
    int[] arr = { 8, 58, 71, 18, 31,
                  32, 63, 92, 43, 3,
                  91, 93, 25, 80, 28 };
    int n = arr.Length;
     
    replace(arr, n);
     
    for(int i = 0; i < n; i++)
    {
        Console.Write(arr[i]+" ");
    }
}
}
 
// This code is contributed by rag2127


Javascript


输出:

18 63 80 25 32 43 80 93 80 25 93 -1 28 -1 -1

由于使用BST,上述解决方案的最坏情况下的时间复杂度也是O(n 2 )。当数组以升序或降序排序时,最坏的情况将会发生。通过使用诸如红黑树之类的平衡树,可以轻松地将复杂度降低为O(nlogn)。