130、分糖果
阿新 • • 發佈:2018-12-31
我的程式碼:
一開始也是想到的是用陣列來儲存但是一看有負數,前後加起來得有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; } }
效率確實有所提高