首页 > 其他 > 详细

Leetcode Candy

时间:2014-11-25 17:45:44      阅读:225      评论:0      收藏:0      [点我收藏+]

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?

对于这道题我一开始把数组排序,然后从小到大给值,后来发现思路错了,看网上的解法,首先建立一个辅助数组用来存每个小朋友得到的糖果数量。初始化数组值为1。之后从左到右扫描一遍,把后一位rating大于前一位rating的糖果数量也增加1个。之后从右到左扫描一遍,把前一位rating比后一位rating大,若前一个的糖果数小于后一个的糖果数,显然是不对的,那么就需要重置。

对于考察左右两边与中间元素关系的题目,均可以使用左右扫描方法

 1 package Candy;
 2 
 3 import java.util.Arrays;
 4 
 5 public class Candy {
 6 public int candy(int[] ratings) {
 7     int [] candy=new int[ratings.length];
 8     for(int i=0;i<candy.length;i++){
 9         candy[i]=1;
10     }
11     for(int i=1;i<candy.length;i++){
12         if(ratings[i]>ratings[i-1]){
13             candy[i]=candy[i-1]+1;
14         }
15     }
16     for(int i=candy.length-2;i>=0;i--){
17         if(ratings[i]>ratings[i+1]&&candy[i]<=candy[i+1])
18         {
19             candy[i]=candy[i+1]+1;
20         }
21     }
22     int sum=0;
23     for(int i=0;i<ratings.length;i++){
24         sum+=candy[i];
25     }
26     return sum;
27     }
28 }

 

Leetcode Candy

原文:http://www.cnblogs.com/criseRabbit/p/4121195.html

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