classSolution: defminSubsequence(self, nums: List[int]) -> List[int]: nums.sort(reverse=True) tot, s = sum(nums), 0 for i, num inenumerate(nums): s += num if s > tot - s: return nums[:i + 1]
[sol1-C++]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classSolution { public: vector<int> minSubsequence(vector<int>& nums){ int total = accumulate(nums.begin(), nums.end(), 0); sort(nums.begin(), nums.end()); vector<int> ans; int curr = 0; for (int i = nums.size() - 1; i >= 0; --i) { curr += nums[i]; ans.emplace_back(nums[i]); if (total - curr < curr) { break; } } return ans; } };
[sol1-Java]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution { public List<Integer> minSubsequence(int[] nums) { inttotal= Arrays.stream(nums).sum(); Arrays.sort(nums); List<Integer> ans = newArrayList<Integer>(); intcurr=0; for (inti= nums.length - 1; i >= 0; --i) { curr += nums[i]; ans.add(nums[i]); if (total - curr < curr) { break; } } return ans; } }
[sol1-C#]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
publicclassSolution { public IList<int> MinSubsequence(int[] nums) { int total = nums.Sum(); Array.Sort(nums); IList<int> ans = new List<int>(); int curr = 0; for (int i = nums.Length - 1; i >= 0; --i) { curr += nums[i]; ans.Add(nums[i]); if (total - curr < curr) { break; } } return ans; } }
int* minSubsequence(int* nums, int numsSize, int* returnSize){ int total = 0; for (int i = 0; i < numsSize; i++) { total += nums[i]; } qsort(nums, numsSize, sizeof(int), cmp); int *ans = (int *)malloc(sizeof(int) * numsSize); int curr = 0, pos = 0; for (int i = numsSize - 1; i >= 0; --i) { curr += nums[i]; ans[pos++] = nums[i]; if (total - curr < curr) { break; } } *returnSize = pos; return ans; }
[sol1-Golang]
1 2 3 4 5 6 7 8 9 10 11 12 13
funcminSubsequence(nums []int) []int { sort.Sort(sort.Reverse(sort.IntSlice(nums))) tot := 0 for _, num := range nums { tot += num } for i, sum := 0, 0; ; i++ { sum += nums[i] if sum > tot-sum { return nums[:i+1] } } }
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12 13 14
var minSubsequence = function(nums) { const total = _.sum(nums); nums.sort((a, b) => a - b); const ans = []; let curr = 0; for (let i = nums.length - 1; i >= 0; --i) { curr += nums[i]; ans.push(nums[i]); if (total - curr < curr) { break; } } return ans; };
复杂度分析
时间复杂度:O(n\log n),其中 n 为 数组的长度。需要对数组进行排序,因此时间复杂度为 O(n\log n)。