LeetCode Candy


https://oj.leetcode.com/problems/candy/


题目的大致意思是,一群孩子排成一队,每个孩子都有一个权值,

要求如果一个孩子的权值比左右的孩子的权值大的话, 就要分到更多的糖果。

求最少的糖果总数。


一开始没有优化,直接对每个孩子的权值进行排序,然后先处理权值小的孩子,再处理权值大的孩子,保证权值大的孩子分到的糖果要比其左右孩子分到的糖果多。

结果超时了,代码如下:


<pre name="code" class="java">public class Solution {
    public int candy(int[] ratings) {
        int n = ratings.length;
        int sum = 0;
        int [] candies = new int [n];
        int [] sortarray = new int [n];
        for(int i=0;i<n;i++){
        	sortarray[i] = ratings[i];
        	candies[i] = 1;
        }
        Arrays.sort(sortarray);
        

        for(int i=1;i<n;i++){
        	int u = sortarray[i];
        	if(u==sortarray[i-1])continue;
        	for(int j=0;j<n;j++){
        		if(u == ratings[j]){

        			if(j-1>=0&&ratings[j]>ratings[j-1]&&candies[j]<candies[j-1]+1){
        				candies[j] = candies[j-1]+1;
        			}
        			if(j+1<n&&ratings[j]>ratings[j+1]&&candies[j]<candies[j+1]+1){
        				candies[j] = candies[j+1]+1;
        			}
        		}
        	}
        }
        for(int i=0;i<n;i++){
        	sum+=candies[i];
        }
        return sum;
    }
}


 



我觉得我这个思路应该是对的,就对代码进行了优化,记录孩子的下标,然后对孩子按权值进行排序。最后AC了。


public class Solution {
	class NODE{
		int index;
		int value;
	}
	class MyComparator implements Comparator<Object>{
		@Override
		public int compare(Object o1, Object o2) {
			// TODO Auto-generated method stub
			NODE node1 = (NODE)o1;
			NODE node2 = (NODE)o2;
			return node1.value - node2.value;
		}
	}

    public int candy(int[] ratings) {
        int n = ratings.length;
        int sum = 0;
        int [] candies = new int [n];
        Solution.NODE [] node = new Solution.NODE[n];
        for(int i=0;i<n;i++){
        	node[i] = new Solution.NODE();
        	candies[i] = 1;
        	node[i].index = i;
        	node[i].value = ratings[i];
        }
        Arrays.sort(node, new MyComparator());
        

        int j;
        for(int i=1;i<n;i++){
    	   
    	   j = node[i].index;
    	   
	       if(j-1>=0&&ratings[j]>ratings[j-1]&&candies[j]<candies[j-1]+1){
	    	   candies[j] = candies[j-1]+1;
	       }
	       if(j+1<n&&ratings[j]>ratings[j+1]&&candies[j]<candies[j+1]+1){
	           candies[j] = candies[j+1]+1;
	       }
	     }
         for(int i=0;i<n;i++){
        	 sum+=candies[i];
         }
         return sum;
    }
}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值