前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Leetcode 561:数组拆分 I Array Partition I

Leetcode 561:数组拆分 I Array Partition I

作者头像
爱写bug
发布2019-08-01 10:36:15
4410
发布2019-08-01 10:36:15
举报
文章被收录于专栏:爱写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:

代码语言:javascript
复制
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:

代码语言:javascript
复制
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

点击查看原文链接即可,跳转到Wiki百科 排序算法页面。

这里简单推荐个:

快速排序(quick sort)—

O(n\log n)

期望时间,

O(n^{2})

最坏情况;对于大的、随机数列表一般相信是最快的已知排序(C语言标准库的qsort()排序用的就是快速排序算法,利用D&C分而治之思想)

代码:

代码语言:javascript
复制
class Solution {
    public int arrayPairSum(int[] nums) {
        qSort(nums,0,nums.length-1);
        int sum=0;
        for (int i=0;i<nums.length;i+=2){
            sum+=nums[i];
        }
        return sum;
    }
    public static void qSort(int[] arr, int head, int tail) {
        if (head >= tail || arr == null || arr.length <= 1) {//基线条件
            return;
        }
        int i = head, j = tail, pivot = arr[(head + tail) / 2];
        while (i <= j) {//递归条件
            while (arr[i] < pivot) ++i;
            while (arr[j] > pivot) --j;
            if (i < j) {
                int t = arr[i];
                arr[i] = arr[j];
                arr[j] = t;
                ++i;
                --j;
            } else if (i == j) ++i;
        }
        qSort(arr, head, j);//递归
        qSort(arr, i, tail);
    }
}

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

点击查看原文链接即可,跳转到Wiki百科 排序算法页面。

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2019-07-03,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 爱写Bug 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 解题思路:
  • 代码:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档