zoukankan      html  css  js  c++  java
  • 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%数据通过。。。一直没有到最后结果。可能是网络有问题,晚上再试。

  • 相关阅读:
    yarn-cli 缓存
    html DOM 的继承关系
    JavaScript basics: 2 ways to get child elements with JavaScript
    svn merge 的区别
    virtualbox 设置windows 于ubuntu虚拟机共享文件夹
    angular 学习理解笔记
    e.which
    痛定思痛
    【转】反思 成长
    日语学习词汇量
  • 原文地址:https://www.cnblogs.com/gousheng/p/7904500.html
Copyright © 2011-2022 走看看