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

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

猜你喜欢

转载自blog.csdn.net/qq_34446716/article/details/85270794
今日推荐