当前位置:网站首页>1299. replace each element with the largest element on the right

1299. replace each element with the largest element on the right

2022-06-22 03:32:00 Mr Gao

1299. Replace each element with the largest element on the right

Give you an array arr , Please replace each element with the largest one on the right , If it's the last element , use -1 Replace .

After all the replacement operations have been completed , Please return this array .

Example 1:

Input :arr = [17,18,5,4,6,1]
Output :[18,6,6,6,1,-1]
explain :

  • Subscript 0 The elements of --> The largest element on the right is the subscript 1 The elements of (18)
  • Subscript 1 The elements of --> The largest element on the right is the subscript 4 The elements of (6)
  • Subscript 2 The elements of --> The largest element on the right is the subscript 4 The elements of (6)
  • Subscript 3 The elements of --> The largest element on the right is the subscript 4 The elements of (6)
  • Subscript 4 The elements of --> The largest element on the right is the subscript 5 The elements of (1)
  • Subscript 5 The elements of --> There are no other elements on the right , Replace with -1

Example 2:

Input :arr = [400]
Output :[-1]
explain : Subscript 0 There are no other elements to the right of the element .

The solution code is as follows :

/** * Note: The returned array must be malloced, assume caller calls free(). */
int* replaceElements(int* arr, int arrSize, int* returnSize){
    
    int max[arrSize];
    int i=0;
    int maxt=arr[arrSize-1];
    for(i=arrSize-1;i>=0;i--){
    
        if(arr[i]>maxt){
    
            max[i]=arr[i];
            maxt=arr[i];
        }
        else{
    
            max[i]=maxt;
        }


    }
    for(i=0;i<arrSize-1;i++){
    
        arr[i]=max[i+1];
    }
    arr[i]=-1;
    *returnSize=arrSize;
    return arr;
    

}
原网站

版权声明
本文为[Mr Gao]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206220319318461.html