zoukankan      html  css  js  c++  java
  • [leetcode] Distribute Candies

    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。还是可以的。

     
  • 相关阅读:
    图解Python 【第八篇】:网络编程-进程、线程和协程
    TCP协议三次握手、四次挥手过程
    OSI七层模型与TCP/IP五层模型
    TCP/IP协议分为哪四层,具体作用是什么。
    app测试中,ios和android的区别
    APP在用户设备发生crash,应该怎么修复
    Android四层架构
    安卓四大组件、六大布局、五大存储
    测试工程师准备找工作,需要准备什么?
    接口测试响应码解析
  • 原文地址:https://www.cnblogs.com/boris1221/p/9304256.html
Copyright © 2011-2022 走看看