130、分糖果

在这里插入图片描述

我的代码:
一开始也是想到的是用数组来存储但是一看有负数,前后加起来得有200000了,就没考虑

class Solution {
    public int distributeCandies(int[] candies) {
        int len = candies.length;
		Arrays.sort(candies);
		if(len == 2){
			return 1;
		}
		
		int count = 0;
		for (int i = 0; i < candies.length-1; i++) {
			if(candies[i] != candies[i+1]){
				count++;
				
			}
			
		}
		count ++;
		if(count >= candies.length /2){
			return candies.length /2;
		}
		return count;
		
    }
}

好嘛,排名靠前的代码,好像就是我的那个思路

 public int distributeCandies(int[] candies) {
        boolean [] b = new boolean[200001];
        int num = 0;
        for (int i : candies){
            if(b[i + 100000]==false){
                b[i + 100000]=true; num++;
            }
        }  
        return Math.min(candies.length/2,num);
    }
}

我用一开始的思路重新试了一下,代码如下

class Solution {
    public int distributeCandies(int[] candies) {
        int tem [] = new int[200001];
		for (int i = 0; i < candies.length; i++) {
			int j = candies[i];
			tem[j+100000] ++;
			
		}
		int count = 0;
		for (int i = 0; i < tem.length; i++) {
			if(tem[i] != 0){
				count ++;
				if(count == candies.length /2){
					break;
				}
			}
			
		}
		return count;
		
    }
}

效率确实有所提高
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值