LeetCode - 561. Array Partition I(数组拆分 I)(贪心和Hash思想)

LeetCode - 561. Array Partition I(数组拆分 I)(贪心和Hash思想)

  • 贪心解法
  • hash思想解法

题目链接
题目

在这里插入图片描述

贪心解法

贪心的解法就是对数组进行排序,因为我们要对数组进行划分,每次选取两个,并且选出最小的那个,所以我们不能浪费那些大的数,所以每次不能浪费更大的数,所以选取相邻的数作为一对。

class Solution {

    public int arrayPairSum(int[] nums) {
        Arrays.sort(nums);
        int res = 0;
        for (int i = 0; i < nums.length; i += 2) 
            res += nums[i];
        return res;
    }
}

hash思想解法

思想也是对数组进行排序,主要是题目中说数的范围在[-10000,10000]之间,所以我们可以开一个20000大小的数组,足以保存下这些数,然后统计每个元素出现的次数,遍历一遍hash数组即可,最多循环20000次。

class Solution {

    public int arrayPairSum(int[] nums) {
        int[] hash = new int[20001];
        for (int i = 0; i < nums.length; i++) 
            hash[nums[i] + 10000]++;
        int res = 0;
        boolean odd = true;
        for (int i = 0; i < hash.length; ) {
            if (hash[i] != 0) {    //原数组中存在
                if (odd) {
                    res += (i - 10000);
                    odd = false;
                } else {
                    odd = true;
                }
                if (--hash[i] == 0) i++; //有可能有重复元素
            } else i++;
        }
        return res;
    }
}

更加优化的解法:

class Solution {

    public int arrayPairSum(int[] nums) {
        int[] hash = new int[20001];
        for (int i = 0; i < nums.length; i++) 
            hash[nums[i] + 10000]++;
        int res = 0;
        boolean odd = true;
        for (int i = 0; i < hash.length; i++) {
            while (hash[i] != 0) {
                if (odd) {
                    res += (i - 10000);
                }
                odd = !odd;
                --hash[i];
            }
        }
        return res;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值