LeetCode 561:数组拆分 I Array Partition I

栏目: 编程工具 · 发布时间: 6年前

内容简介:文章全部来自公众号:爱写bugGiven an array of

文章全部来自公众号:爱写bug

算法是一个程序的灵魂。

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.

给定长度为 2n 的数组, 你的任务是将这些数分成 n 对, 例如 (a1, b1), (a2, b2), ..., (an, bn) ,使得从1 到 n 的 min(ai, bi) 总和最大。

Example 1:

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).

Note:

  1. n is a positive integer, which is in the range of [1, 10000].
  2. All the integers in the array will be in the range of [-10000, 10000].

提示:

  1. n 是正整数,范围在 [1, 10000].
  2. 数组中的元素范围在 [-10000, 10000].

解题思路:

​ 其实就是把 数组排序,然后按顺序 每两个数既是一对,每对的第一个数累加之和即为所求。就是考一下各类 排序 算法的性能。

先使用内置 sort() 函数理解一下思路:

Java:

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

扩展:

维基百科上对 排序算法 介绍的非常详细,并且进行了归类比较,地址: https://zh.wikipedia.org/wiki/%E6%8E%92%E5%BA%8F%E7%AE%97%E6%B3%95

这里简单推荐两个:

  • 快速排序 (quick sort)— 期望时间, 最坏情况;对于大的、随机数列表一般相信是最快的已知排序(C语言标准库的 qsort() 排序用的就是快速排序算法,利用递归和分而治之思想)
  • 桶排序 (bucket sort)— ;需要 额外空间(典型的牺牲空间换时间)

冒泡排序、选择排序都是比较简单容易理解,复杂度是 n^2 ,所以不再赘述。

LeetCode 561:数组拆分 I Array Partition I

LeetCode 561:数组拆分 I Array Partition I


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Boolean Reasoning

Boolean Reasoning

Brown, Frank Markham / 2003-4 / $ 19.15

A systematic treatment of Boolean reasoning, this concise, newly revised edition combines the works of early logicians with recent investigations, including previously unpublished research results. Th......一起来看看 《Boolean Reasoning》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具