1. 程式人生 > >[leetcode] Distribute Candies

[leetcode] Distribute Candies

imu 組元 ++ dot rep present 運行時 inter hset

Given an integer array with even length, where different numbers in this array represent different kinds of candies. Each number means one candy of the corresponding kind. You need to distribute these candies equally in number to brother and sister. Return the maximum number of kinds of candies the sister could gain.

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. The length of the given array is in range [2, 10,000], and will be even.
  2. The number in given array is in range [-100,000, 100,000].

分析:題目比較簡單的,翻譯一下就是:1、數組長度是偶數;2、將數組分成兩個部分,每個部分元素個數相同;3、求使得某個部分數組元素種類最多的種類數。 代碼如下:
 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。還是可以的。

[leetcode] Distribute Candies