码迷,mamicode.com
首页 > 其他好文 > 详细

Candy

时间:2015-05-19 00:36:46      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:

Candy

问题:

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?

思路:

  左到右一遍 右到左一遍 

我的代码:

技术分享
public class Solution {
    public int candy(int[] ratings) {
        if(ratings==null || ratings.length==0)  return 0;
        if(ratings.length == 1) return 1;
        int len = ratings.length;
        int[] nums = new int[len];
        int k = 1;
        for(int i=1; i<len; i++)
        {
            if(ratings[i] < ratings[i+1])
            {
                nums[i] = k;
                nums[i+1] = k+1;
                k++;
            }
            else
            {
                k = 1;
                nums[i] = Math.max(nums[i], k);
                nums[i+1] = Math.max(nums[i+1], k);
            }
        }
        k = 1;
        for(int i=len-1; i>=1; i--)
        {
            if(ratings[i-1] > ratings[i])
            {
                nums[i] = Math.max(nums[i], k);
                nums[i-1] = Math.max(nums[i-1], k+1);
                k++;
            }
            else
            {
                k = 1;
                nums[i-1] = Math.max(nums[i-1], k);
                nums[i] = Math.max(nums[i], k);
            }
        }
        int rst = 0;
        for(int num : nums) rst += num;
        return rst;
    }
}
View Code

他人代码:

技术分享
public class Solution {
    public int candy(int[] ratings) {
        if(ratings == null || ratings.length == 0) {
            return 0;
        }

        int[] count = new int[ratings.length];
        Arrays.fill(count, 1);
        int sum = 0;
        for(int i = 1; i < ratings.length; i++) {
            if(ratings[i] > ratings[i - 1]) {
                count[i] = count[i - 1] + 1;
            }
        }

        for(int i = ratings.length - 1; i >= 1; i--) {
            sum += count[i];
            if(ratings[i - 1] > ratings[i] && count[i - 1] <= count[i]) {  // second round has two conditions
                count[i-1] = count[i] + 1;
            }
        }
        sum += count[0];
        return sum;
    }
}
View Code

 

学习之处:

  • 一个数组有以下几个特点:上升沿,下降沿,波峰,波谷,和是定值,若数组值的取值范围是0--n则正好对应A[index] = index,可以基于此判断缺少那个数字
  • 常用的测试用例 null [0] [1,2] [2,1] [1,2,3] [1,2,1]

Candy

标签:

原文地址:http://www.cnblogs.com/sunshisonghit/p/4513311.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!