zoukankan      html  css  js  c++  java
  • 【leetcode】561. Array Partition I

    原题:

    Given an array of 2n integers, your task is to group these integers into n pairs of integer, say (a1, b1), (a2, b2), ..., (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as possible.

    解析:

    数组分割1
    给一组2n个整数,分割为n组,一组2个数,使min(a,b)之和最大
    Example:
    Input: [1,4,3,2]
    Output: 4
    Explanation: n is 2, and the maximum sum of pairs is 4 = min(1, 2) + min(3, 4).

    我的解法

    很明显每组数值越接近,浪费的数值越小,所得的总和最大,我的解法如下

    public class ArrayPartitionI {
        public static int arrayPartitionI(int[] array) {
            Arrays.sort(array);
            int sum = 0;
            for (int i = 0; i < array.length - 1; i += 2) {
                sum += array[i];
            }
            return sum;
        }
    }
    

    最优解法

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

    哈哈几乎一样,后来想了一下不用length-1也可以的

  • 相关阅读:
    eazsy-ui 按钮样式
    sql
    事务
    spring-aop切入点配置
    改变HTML文件上传控件样式(隐藏默认样式 用点击图片间接调用)
    JS的几条规则
    JS高阶函数
    JAVA中的工厂方法模式和抽象工厂模式
    JAVA单例模式
    JAVA对象创建的过程
  • 原文地址:https://www.cnblogs.com/shanelau/p/7118719.html
Copyright © 2011-2022 走看看