标签:hash 简单的 xpl 案例 repr put ash question imu
Example 1:
Input: candies = [1,1,2,2,3,3] Output: 3 Explanation: There are three different kinds of candies (1, 2 and 3), and two candies for each kind. Optimal distribution: The sister has candies [1,2,3] and the brother has candies [1,2,3], too. The sister has three different kinds of candies.
Example 2:
Input: candies = [1,1,2,3] Output: 2 Explanation: For example, the sister has candies [2,3] and the brother has candies [1,1]. The sister has two different kinds of candies, the brother has only one kind of candies.
Note:
1 class Solution { 2 public int distributeCandies(int[] candies) { 3 Arrays.sort(candies); 4 int number = candies.length / 2; 5 int cur_n = 1; 6 for ( int i = 1 ; i < candies.length ; i ++ ){ 7 if ( candies[i] != candies[i-1] && cur_n < number ) cur_n++; 8 } 9 return cur_n; 10 } 11 }
运行时间68ms。这种方法刚开始我以为数组是有序的,结果有个案例过不了,发现测试中有无序的,所以加了一句排序代码。
因为是无序的,所以考虑使用set。代码如下:
1 class Solution { 2 public int distributeCandies(int[] candies) { 3 int number = candies.length / 2; 4 Set<Integer> set = new HashSet<>(); 5 for ( int i = 0 ; i < candies.length ; i ++ ){ 6 if ( set.size() < number ) set.add(candies[i]); 7 } 8 return set.size(); 9 } 10 }
运行时间45ms。还是可以的。
标签:hash 简单的 xpl 案例 repr put ash question imu
原文地址:https://www.cnblogs.com/boris1221/p/9304256.html