zoukankan      html  css  js  c++  java
  • [leet code 135]candy

    1 题目

    There are N children standing in a line. Each child is assigned a rating value.

    You are giving candies to these children subjected to the following requirements:

    • Each child must have at least one candy.
    • Children with a higher rating get more candies than their neighbors.

    What is the minimum candies you must give?

    2 思路

    按照网上的思路,每个孩子至少有一个糖果,先从左到右遍历一遍,写出递增的糖果数,再从右到左遍历一遍完成递减的糖果数。这种大小与左右两边数据相关的问题,均可以采用这个思路。另外,有另一种空间复杂度O(1),时间复杂度O(n)的思路,可以参考http://www.cnblogs.com/felixfang/p/3620086.html

    3 代码

     public int candy(int[] ratings) {  
            if(ratings == null || ratings.length == 0)  
            {  
                return 0;  
            }  
            int[] candyNums = new int[ratings.length];  
            candyNums[0] = 1;  
                 
            for(int i = 1; i < ratings.length; i++)  
            {  
                if(ratings[i] > ratings[i-1])  //如果第i个孩子比第i - 1孩子等级高,
                {  
                    candyNums[i] = candyNums[i-1]+1;  
                }  
                else //每人至少有一个糖果
                {  
                    candyNums[i] = 1;  
                }  
            }  
             
            for(int i = ratings.length-2; i >= 0; i--)  
            {  
                
                if(ratings[i] > ratings[i + 1] && candyNums[i] <= candyNums[ i + 1]) //如果第i个孩子比第i + 1孩子等级高并且糖果比i+1糖果少 
                {  
                     candyNums[i] = candyNums[i + 1] + 1;
                }    
            }  
            
            int total = 0;
            for (int i = 0; i < candyNums.length; i++) {
                total += candyNums[i];
            }
            
            return total;  
        }
  • 相关阅读:
    单位表示
    linux 文件权限
    php中高级基础知识点
    CodeIgniter配置之SESSION
    提高PHP开发质量的36个方法(精品)
    数据库优化举例详解
    ajax 跨域解决 网上资料
    static(静态)关键字
    假如java类里的成员变量是自身的对象
    Java 静态代码块&构造代码块&局部代码块
  • 原文地址:https://www.cnblogs.com/lingtingvfengsheng/p/4304505.html
Copyright © 2011-2022 走看看