动态规划--更新数组值为其右边最大值

来源:互联网 发布:caxa编程助手 编辑:程序博客网 时间:2024/05/22 13:51

需求:

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].

样例:Give nums = [16, 17, 4, 3, 5, 2], change nums to [17, 5, 5, 5, 2, -1]
You should do it in place.

分析:

主要思想是动态规划,从后向前考虑,除了最后两个元素较为特殊之外,其余每个元素的新值都是max{后面一个元素, 后面一个元素的后面最大值}

1、数组如果是null或者长度是0,那么不需要处理

2、如果数组长度是1,那么直接赋值-1,如果长度是2,那么[0]=[1], [1]=-1

3、对于长度大于2的,需要使用动态规划思想从后向前考虑。创建新数组int max[nums.length],max[nums.length-1]=-1,max[nums.length-2]=nums[nums.length-1],对于0~(nums.length-3)的元素,每个元素的新值为max[i]=Math.max(nums[i], max[i+1])

代码:

public class Solution {    /*     * @param : An array of integers.     * @return: nothing     */    public void arrayReplaceWithGreatestFromRight(int[] nums) {        // Write your code here.        if(nums == null || nums.length == 0){            return;        }                //对长度是1或2的数组单独处理        if(nums.length == 1){            nums[0] = -1;        }        else if(nums.length == 2){            nums[0] = nums[1];            nums[1] = -1;        }        else{            //创建新的数组,代表新的值            int[] max = new int[nums.length];                        max[nums.length-1] = -1;            max[nums.length-2] = nums[nums.length-1];            for(int i = nums.length-3; i >= 0; i--){                max[i] = Math.max(nums[i+1], max[i+1]);            }                        //将数组值进行更新            for(int i = 0; i < nums.length; i++){                nums[i] = max[i];            }        }    }}



阅读全文
0 0