首页 > 其他分享 >leetcode 561. Array Partition I

leetcode 561. Array Partition I

时间:2023-05-30 18:04:17浏览次数:45  
标签:sort ... 10000 nums min 561 Partition range Array

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.

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. 解法:
class Solution(object):
    def arrayPairSum(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        # [1,4,3,2]=>sort, [1,2,3,4]=>1+3=4
        # [1,2,3,5,12,19,20,21]=>sorted => greedy, 1+3+12+20
        nums.sort()
        return sum(nums[0::2])

我自己想的是贪心思路,

先假设这个数组排序了,例如:[1,2,3,5,12,19,20,21]

min(ai, bi)明显是Min(20,21),因为21最大。

剩下的就是递归解:

[1,2,3,5,12,19】

思路类似。

 

 

其他人的分析:

Let me try to prove the algorithm…

  1. Assume in each pair i, bi >= ai.
  2. Denote Sm = min(a1, b1) + min(a2, b2) + ... + min(an, bn). The biggest Sm is the answer of this problem. Given 1, Sm = a1 + a2 + ... + an.
  3. Denote Sa = a1 + b1 + a2 + b2 + ... + an + bn. Sa is constant for a given input.
  4. Denote di = |ai - bi|. Given 1, di = bi - ai. Denote Sd = d1 + d2 + ... + dn.
  5. So Sa = a1 + a1 + d1 + a2 + a2 + d2 + ... + an + an + dn = 2Sm + Sd => Sm = (Sa - Sd) / 2. To get the max Sm, given Sa is constant, we need to make Sd as small as possible.
  6. So this problem becomes finding pairs in an array that makes sum of di (distance between ai and bi) as small as possible. Apparently, sum of these distances of adjacent elements is the smallest. If that’s not intuitive enough, see attached picture. Case 1 has the smallest Sd.

其他解法就是trick,利用All the integers in the array will be in the range of [-10000, 10000].hash来做桶排序。

class Solution(object):
    def arrayPairSum(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        # bucket sort
        num_range = 20001
        sort_map = [0]*num_range
        for n in nums:
            sort_map[n+10000] += 1
        ans = 0
        odd = True
        for i in range(0, num_range):
            while sort_map[i]:
                if odd:
                    ans += (i-10000)
                sort_map[i] -= 1
                odd = not odd
        return ans

 

标签:sort,...,10000,nums,min,561,Partition,range,Array
From: https://blog.51cto.com/u_11908275/6381151

相关文章

  • leetcode 350. Intersection of Two Arrays II
    Giventwoarrays,writeafunctiontocomputetheirintersection.Example:Givennums1=[1,2,2,1],nums2=[2,2],return[2,2].Note:Eachelementintheresultshouldappearasmanytimesasitshowsinbotharrays.Theresultcanbeinanyorder.Foll......
  • leetcode 53. Maximum Subarray
    Givenanintegerarraynums,findthecontiguoussubarray (containingatleastonenumber)whichhasthelargestsumandreturnitssum.Example:Input:[-2,1,-3,4,-1,2,1,-5,4],Output:6Explanation: [4,-1,2,1]hasthelargestsum=6.Followup:Ifyouhavef......
  • Erlang 对dict、maps、array的部分性能测试
    竖轴:时间(微秒)横轴(数据量)备注(maps与dict的key是{name,整数}与整数在速度上差别不大,array的key是正整数)结论数据量在32-10000用maps的各种操作速度更快(但内存稍多,引用官方描述,此处没测)数据量1万以上,如果键是正整数,array与maps性能相当(官方推荐用array)数据量接近32个的时候是map......
  • 10ArrayList&学生管理系统
    1.ArrayList集合和数组的优势对比:长度可变,自动扩容。添加数据的时候不需要考虑索引,默认将数据添加到末尾1.1ArrayList类概述什么是集合​ 提供一种存储空间可变的存储模型,存储的数据容量可以发生改变ArrayList集合的特点​ 长度可以变化,只能存储引用数据类型。在存......
  • ArrayList的实现原理
    一、 ArrayList概述:  ArrayList是基于数组实现的,是一个动态数组,其容量能自动增长,类似于C语言中的动态申请内存,动态增长内存。   ArrayList不是线程安全的,只能用在单线程环境下,多线程环境下可以考虑用Collections.synchronizedList(Listl)函数返回一个线程安全的ArrayList......
  • DataFrame转为数组Array
    DataFrame转为数组Array有文本数据如下:目标:将文本数据以数组形式呈现步1:读入数据importpandasaspddata=pd.read_table(file_path,sep=',',header=None)数据呈现如下:步2:将dataframe转为数组data_x=np.array(data[0].tolist())data_y=np.array(data[1].tol......
  • Arraylist1
    importjava.time.LocalDate;importjava.util.ArrayList;importjava.util.List;publicclassList1{publicstaticvoidmain(String[]args){//集合类(collection):长度可变,不同类型//1--创建对象ArrayListarrayList=newArrayList();//创建对象(......
  • LeetCode-Java题解 977. Squares of a Sorted Array
    题目地址:977.SquaresofaSortedArray解题思路:    又是一道双指针的题目,看见秒想到双指针(平方直接调用sort方法也行,但是这么写这题就没意思了)。但是,我一直在想,不增加空间消耗的情况下,如何进行排列,想了半天把自己绕进去了。开辟一个新数组,倒序放置就非常简单了。一定要利......
  • 错误解决:These dependencies were not found: core-js/modules/es.array.push.js
    错误描述执行npmrundev后报错:Thesedependencieswerenotfound:core-js/modules/es.array.push.jsin./node_modules/@babel/runtime/helpers/objectSpread2.js,./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/@vue/cli-pluvue?vue&type=script&la......
  • php中array用法
    在PHP中,array是一种非常重要的数据类型,通常用于存储和操作多个值。使用array可以将多个变量组合成单个便于管理的结构,并通过索引、键或其他方式进行访问和操纵。以下是一些PHP中array的常见用法:创建一个空的数组php复制代码$arr=array();创建一个包含多个元素的数组ph......