• lintcode735. Replace With Greatest From Right


    Given an array of integers, replace every element with the next greatest element (greatest element on the right side) in the array. Since there is no element next to the last element, replace it with -1. For example, if the array is [16, 17, 4, 3, 5, 2], then it should be modified to [17, 5, 5, 5, 2, -1].

    最初的思路代码(超时)

    class Solution {
    public:
        /*
         * @param : An array of integers.
         * @return: nothing
         */
        void arrayReplaceWithGreatestFromRight(vector<int> &nums) {
            // Write your code here.
            int len = nums.size();
            int max = nums[len - 1];
            nums[len - 1] = -1;
            for (int i = len - 2; i >= 0; i--) {
                int temp = nums[i];
                nums[i] = max;
                if (temp > max) {
                    max = temp;
                }
            }
    
        }
    };

    从后往前的方法:

     1 class Solution {
     2 public:
     3     /*
     4      * @param : An array of integers.
     5      * @return: nothing
     6      */
     7     void arrayReplaceWithGreatestFromRight(vector<int> &nums) {
     8         // Write your code here.
     9         int len = nums.size();
    10         int max = nums[len - 1];
    11         nums[len - 1] = -1;
    12         for (int i = len - 2; i >= 0; i--) {
    13             int temp = nums[i];
    14             nums[i] = max;
    15             if (temp > max) {
    16                 max = temp;
    17             }
    18         }
    19 
    20     }
    21 };

    目前一直是79%数据通过。。。一直没有到最后结果。可能是网络有问题,晚上再试。

  • 相关阅读:
    AESUtil_1
    ELK配置
    Centos7上安装docker
    Excel大批量数据导出
    Redis5.0.6安装完整步骤
    idea远程打断点
    [HNOI2016] 序列
    [TJOI2017] 异或和
    洛谷 P4933 大师
    洛谷 P1950 长方形_NOI导刊2009提高(2)
  • 原文地址:https://www.cnblogs.com/gousheng/p/7904500.html
Copyright © 2020-2023  润新知