1. 程式人生 > >算法--leetcode 561. Array Partition I

算法--leetcode 561. Array Partition I

hash vector容器 一個 say 相加 整數 += blog hashtable

題目:

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組,求每一組中的較小值,求這些較小值相加的最大和。

輸入輸入樣例:

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

Python 解:

思路:使用自帶函數sorted排序,將索引為0,2,4,6....n-2的數相加(即奇數順序的數),時間復雜度為nlog(n)

class Solution(object):
    def arrayPairSum(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        
""" return sum(sorted(nums)[::2])

C++解:

思路:不懂,時間復雜度為 O(n)

語法要點:使用了vector容器,vector<int>& nums直接將 nums 數組賦值給vector容器。

vector意為向量,可以理解為數組的增強版,封裝了許多對自身操作的函數。

class Solution {
public:
    int arrayPairSum(vector<int>& nums) {
        int ret = 0;
        bool flag = true
; array<int, 20001> hashtable{ 0 }; for (const auto n : nums) { ++hashtable[n + 10000]; } for (int i = 0; i < 20001;) { if (hashtable[i] > 0) { if (flag) { flag = false; ret += (i - 10000); --hashtable[i]; } else { flag = true; --hashtable[i]; } } else ++i; } return ret; } };

算法--leetcode 561. Array Partition I