📌  相关文章
📜  用右侧最大的元素替换每个元素

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

用右侧最大的元素替换每个元素

给定一个整数数组,用数组中的下一个最大元素(右侧最大元素)替换每个元素。由于最后一个元素旁边没有元素,因此将其替换为 -1。例如,如果数组是{16, 17, 4, 3, 5, 2},那么应该修改为{17, 5, 5, 5, 2, -1}。

我们强烈建议您单击此处并进行练习,然后再继续使用解决方案。

这个问题与这篇文章非常相似,解决方案也相似。
一种天真的方法是运行两个循环。外循环将从左到右一一挑选数组元素。内部循环将找到在拾取元素之后存在的最大元素。最后,外循环将用内循环找到的最大元素替换拾取的元素。该方法的时间复杂度为 O(n*n)。
一种棘手的方法是使用一次遍历数组来替换所有元素。思路是从最右边的元素开始,一个一个地向左边移动,一直跟踪最大的元素。用最大元素替换每个元素。

C++
// C++ Program to replace every element with the greatest
// element on right side
#include 
using namespace std;
 
/* Function to replace every element with the
next greatest element */
void nextGreatest(int arr[], int size)
{
    //Initialise maxFromRight with -1
    int maxFromRight = -1;
    int n = arr.length;
      // run loop from last and replace maxFromRight with the element in the array
    for(int i= n-1; i>=0;i--) {
      int temp = maxFromRight;
      if(arr[i]> maxFromRight){
        //replacing only array element with maxFromRight in case element is bigger
        maxFromRight = arr[i];
      }
      arr[i] = temp;
    }
    return arr;
}
 
/* A utility Function that prints an array */
void printArray(int arr[], int size)
{
    int i;
    for (i = 0; i < size; i++)
        cout << arr[i] << " ";
    cout << endl;
}
 
/* Driver program to test above function */
int main()
{
    int arr[] = {16, 17, 4, 3, 5, 2};
    int size = sizeof(arr)/sizeof(arr[0]);
    nextGreatest (arr, size);
    cout << "The modified array is: \n";
    printArray (arr, size);
    return (0);
}
 
// This is code is contributed by rathbhupendra


C
// C Program to replace every element with the greatest
// element on right side
#include 
 
/* Function to replace every element with the
   next greatest element */
void nextGreatest(int arr[], int size)
{
  // Initialize the next greatest element
  int max_from_right =  arr[size-1];
 
  // The next greatest element for the rightmost element
  // is always -1
  arr[size-1] = -1;
 
  // Replace all other elements with the next greatest
  for(int i = size-2; i >= 0; i--)
  {
    // Store the current element (needed later for updating
    // the next greatest element)
    int temp = arr[i];
 
    // Replace current element with the next greatest
    arr[i] = max_from_right;
 
    // Update the greatest element, if needed
    if(max_from_right < temp)
       max_from_right = temp;
  }
}
 
/* A utility Function that prints an array */
void printArray(int arr[], int size)
{
  int i;
  for (i=0; i < size; i++)
    printf("%d ", arr[i]);
  printf("\n");
}
 
/* Driver program to test above function */
int main()
{
  int arr[] = {16, 17, 4, 3, 5, 2};
  int size = sizeof(arr)/sizeof(arr[0]);
  nextGreatest (arr, size);
  printf ("The modified array is: \n");
  printArray (arr, size);
  return (0);
}


Java
// Java Program to replace every element with the
// greatest element on right side
import java.io.*;
 
class NextGreatest
{
    /* Function to replace every element with the
       next greatest element */
    static void nextGreatest(int arr[])
    {
        int size = arr.length;
 
        // Initialize the next greatest element
        int max_from_right =  arr[size-1];
 
        // The next greatest element for the rightmost
        // element is always -1
        arr[size-1] = -1;
 
        // Replace all other elements with the next greatest
        for (int i = size-2; i >= 0; i--)
        {
            // Store the current element (needed later for
            // updating the next greatest element)
            int temp = arr[i];
 
            // Replace current element with the next greatest
            arr[i] = max_from_right;
 
            // Update the greatest element, if needed
            if(max_from_right < temp)
            max_from_right = temp;
        }
    }
 
    /* A utility Function that prints an array */
    static void printArray(int arr[])
    {
        for (int i=0; i < arr.length; i++)
        System.out.print(arr[i]+" ");
    }
 
    public static void main (String[] args)
    {
        int arr[] = {16, 17, 4, 3, 5, 2};
        nextGreatest (arr);
        System.out.println("The modified array:");
        printArray (arr);
    }
}
/*This code is contributed by Devesh Agrawal*/


Python3
# Python Program to replace every element with the
# greatest element on right side
 
# Function to replace every element with the next greatest
# element
def nextGreatest(arr):
 
    size = len(arr)
 
    # Initialize the next greatest element
    max_from_right = arr[size-1]
 
    # The next greatest element for the rightmost element
    # is always -1
    arr[size-1] = -1
 
    # Replace all other elements with the next greatest
    for i in range(size-2,-1,-1):
 
        # Store the current element (needed later for updating
        # the next greatest element)
        temp = arr[i]
 
        # Replace current element with the next greatest
        arr[i]=max_from_right
 
        # Update the greatest element, if needed
        if max_from_right< temp:
            max_from_right=temp
 
# Utility function to print an array
def printArray(arr):
    for i in range(0,len(arr)):
        print (arr[i],end=" ")
 
# Driver function to test above function
arr = [16, 17, 4, 3, 5, 2]
nextGreatest(arr)
print ("Modified array is")
printArray(arr)
# This code is contributed by Devesh Agrawal


C#
// C# Program to replace every element with the
// greatest element on right side
using System;
 
class GFG {
     
    /* Function to replace every element with
    the    next greatest element */
    static void nextGreatest(int []arr)
    {
        int size = arr.Length;
 
        // Initialize the next greatest element
        int max_from_right = arr[size-1];
 
        // The next greatest element for the
        // rightmost element is always -1
        arr[size-1] = -1;
 
        // Replace all other elements with the
        // next greatest
        for (int i = size-2; i >= 0; i--)
        {
            // Store the current element (needed
            // later for updating the next
            // greatest element)
            int temp = arr[i];
 
            // Replace current element with
            // the next greatest
            arr[i] = max_from_right;
 
            // Update the greatest element, if
            // needed
            if(max_from_right < temp)
            max_from_right = temp;
        }
    }
 
    /* A utility Function that prints an array */
    static void printArray(int []arr)
    {
        for (int i=0; i < arr.Length; i++)
        Console.Write(arr[i]+" ");
    }
 
    public static void Main ()
    {
        int []arr = {16, 17, 4, 3, 5, 2};
        nextGreatest (arr);
        Console.WriteLine("The modified array:");
        printArray (arr);
    }
}
 
/* This code is contributed by vt_m.*/


PHP
= 0; $i--)
    {
        // Store the current element (needed
        // later for updating the next
        // greatest element)
        $temp = $arr[$i];
     
        // Replace current element with the
        // next greatest
        $arr[$i] = $max_from_right;
     
        // Update the greatest element,
        // if needed
        if($max_from_right < $temp)
        $max_from_right = $temp;
    }
}
 
// A utility Function that prints an array
function printArray($arr, $size)
{
    for ($i = 0; $i < $size; $i++)
        echo $arr[$i] . " ";
    echo "\n";
}
 
// Driver Code
$arr = array(16, 17, 4, 3, 5, 2);
$size = count($arr);
nextGreatest ($arr, $size);
echo "The modified array is: \n";
printArray ($arr, $size);
 
// This code is contributed by
// rathbhupendra
?>


Javascript


输出:

The modified array is:
17 5 5 5 2 -1

时间复杂度: O(n),其中 n 是数组中的元素数。