zoukankan      html  css  js  c++  java
  • 575. 分糖果『简单』

    题目来源于力扣(LeetCode

    一、题目

    575. 分糖果

    提示:

    • 数组的长度为[2, 10,000],并且确定为偶数。
    • 数组中数字的大小在范围[-100,000, 100,000]内。

    二、解题思路

    2.1 Set集合方式

    1. 遍历 candies 数组,将数组元素添加到 Set 集合中

    2. 返回结果,糖果种类(即 Set 集合的大小)大于 candies 数组长度的一半时,返回数组长度一半

    3. 否则返回糖果种类(即 Set 集合的大小)

    糖果是平均的,两个人的糖果数量必须是相同的

    2.2 哈希数组方式

    1. 创建作为哈希映射的数组长度为 200001

    2. 遍历 candies 数组,通过哈希映射的数组记录下不同的元素的数量

    3. 返回结果,不同元素的数量大于 candies 数组长度的一半时,返回数组长度一半

    4. 否则返回不同元素的数量

    糖果是平均的,两个人的糖果数量必须是相同的

    三、代码实现

    3.1 Set集合方式

    public static int distributeCandies(int[] candies) {
        Set<Integer> set = new HashSet<>();
        for (int i : candies) {
            set.add(i);
        }
        // set 中的长度即糖果的种类
        int numKind = set.size();
        int len = candies.length;
        // 糖果种类大于 candies 数组长度的一半时,返回数组长度一半
        if (numKind > len / 2) {
            return len / 2;
        }
        // 返回糖果种类数量
        return numKind;
        // return Math.min(numKind, len);
    }
    

    3.2 哈希数组方式

    public static int distributeCandies2(int[] candies) {
        // -100000 ~ 100000
        // 定义布尔类型的数组作为哈希映射,元素默认值为 false
        boolean[] bucket = new boolean[200001];
        int count = 0;
        for (int i : candies) {
            int j = i + 100000;
            // 哈希映射数组中对应的索引上 boolean 值为 false 时
            if (!bucket[j]) {
                // boolean 值改变为 true
                bucket[j] = true;
                // 记录不同元素的数量,即糖果的种类数量
                count++;
            }
        }
        int average = candies.length / 2;
        if (count < average) {
            return count;
        }
        return average;
        //  return count < average ? count : average;
    }
    

    四、执行用时

    4.1 Set集合方式

    4.2 哈希数组方式

    五、部分测试用例

    public static void main(String[] args) {
    	int[] candies = {1, 1, 2, 2, 3, 3};  // output:3
    //    int[] candies = {1, 1, 2, 3};  // output:2
        int result = distributeCandies(candies);
        System.out.println(result);
    }
    
  • 相关阅读:
    hibernate4 使用及 新特性
    hibernate数据库配置
    Hibernate 插入,修改,删除,查询语句
    Hibernate之HQL总结
    简单编程题
    冒泡排序
    Accelerating Enum-Based Dictionaries with Generic EnumComparer
    本机自定义域名跳转
    ckeditor自己用的配置文件config.js
    RazorExtensions Templated Razor Delegates
  • 原文地址:https://www.cnblogs.com/zhiyin1209/p/12913208.html
Copyright © 2011-2022 走看看