Algorithm--leetcode 561. Array Partition I

Source: Internet
Author: User

Topic:

Given an array of 2n integers, your task was 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.

Test instructions

Give an array of length 2n, divide them into groups of N, and ask for smaller values in each group to find the maximum sum of these smaller values.

Enter an input sample:
Input: [1,4,3,2]output:4explanation:n is 2, and the maximum sum of pairs is 4 = min (1, 2) + min (3, 4).

Note:
    1. n is a positive integer (positive integer), which is in the range of [1, 10000].
    2. All the integers in the array would be in the range of [-10000, 10000].

Python Solution:

Idea: Use the sorted function to sort, add the number of indexes to 0,2,4,6....n-2 (that is, the number of odd orders), the time complexity is Nlog (n)

class solution (Object):     def arraypairsum (Self, nums):         """         : Type Nums:list[int]        : rtype:int        "" "        return sum (sorted (nums) [: : 2])        
C + + Solution:

Idea: don't understand, time complexity is O (n)

Syntax essentials: Using the vector container,vector<int>& nums directly assigns the nums array to the vector container.

Vector, which can be understood as an enhanced version of the array, encapsulates a number of functions that operate on its own.

classSolution { Public:    intArraypairsum (vector<int>&nums) {        intRET =0; BOOLFlag =true; Array<int,20001> hashtable{0 };  for(ConstAuto N:nums) {            ++hashtable[n +10000]; }         for(inti =0; I <20001;) {            if(Hashtable[i] >0) {                if(flag) {flag=false; RET+ = (I-10000); --Hashtable[i]; } Else{flag=true; --Hashtable[i]; }            } Else++i; }        returnret; }};

Algorithm--leetcode 561. Array Partition I

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.