(Easy) Distribute Candies LeetCode

客官°小女子只卖身不卖艺 2021-10-29 10:46 353阅读 0赞

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:

  1. Input: candies = [1,1,2,2,3,3]
  2. Output: 3
  3. Explanation:
  4. There are three different kinds of candies (1, 2 and 3), and two candies for each kind.
  5. Optimal distribution: The sister has candies [1,2,3] and the brother has candies [1,2,3], too.
  6. The sister has three different kinds of candies.

Example 2:

  1. Input: candies = [1,1,2,3]
  2. Output: 2
  3. Explanation: For example, the sister has candies [2,3] and the brother has candies [1,1].
  4. 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].

Accepted

76,485

Submissions

127,393

  1. import java.util.*;
  2. class Solution {
  3. public int distributeCandies(int[] candies) {
  4. if(candies.length == 0 || candies == null){
  5. return 0;
  6. }
  7. Arrays.sort(candies);
  8. Stack<Integer> stack = new Stack<Integer>();
  9. for(int i = 0 ; i<candies.length; i++){
  10. if(stack.empty()){
  11. stack.push(candies[i]);
  12. }
  13. else{
  14. if(stack.peek()!=candies[i]){
  15. stack.push(candies[i]);
  16. }
  17. }
  18. }
  19. if(stack.size()>=candies.length/2){
  20. return candies.length/2;
  21. }
  22. else{
  23. return stack.size();
  24. }
  25. }
  26. }

转载于:https://www.cnblogs.com/codingyangmao/p/11285829.html

发表评论

表情:
评论列表 (有 0 条评论,353人围观)

还没有评论,来说两句吧...

相关阅读