首页 > 其他 > 详细

[leet code 135]candy

时间:2015-02-28 00:04:55      阅读:432      评论:0      收藏:0      [点我收藏+]

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;  
    }

 

[leet code 135]candy

原文:http://www.cnblogs.com/lingtingvfengsheng/p/4304505.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!