【LeetCode】數組-6(561)-Array Partition I(比較抽象的題目)
阿新 • • 發佈:2017-08-19
you num pos 代碼 images 抽象 時間 思路 bsp ,求最小並求和。??【註意】指針每次累加 2
題目描述:兩句話發人深思啊。。。。
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.
感覺題目的大致意思就是把數組分成很多個二元數組,對它們以求最小值的方式求和,使得和最大。
思路:
最開始的思路,現在還不知道對不對,就是先排序數組,使用一個指針向後遍歷
【正確代碼】 一次寫對~
1 class Solution { 2 public int arrayPairSum(int[] nums) { 3 if (nums.length % 2 != 0 || nums == null) { 4 return -1; 5 } 6 Arrays.sort(nums); 7 int maxSum = 0; 8 for (int i = 0; i < nums.length - 1; i += 2) { 9 maxSum += Math.min(nums[i], nums[i + 1]); 10 } 11 return maxSum; 12 } 13 }
時間復雜度:O(n*logn)
空間復雜度:O(n*logn)
【LeetCode】數組-6(561)-Array Partition I(比較抽象的題目)