761. Smallest Subset

Given an array of non-negative integers. Our task is to find minimum number of elements such that their sum should be greater than the sum of rest of the elements of the array.

 

Given nums = [3, 1, 7, 1], return 1
Given nums = [2, 1, 2], return 2

 

我觉得我这个解法还是时间复杂度有点高,并不是很巧妙,基本就是无脑

 1 int minElements(vector<int> &arr) {
 2         // write your code here
 3         sort(arr.begin(), arr.end(), greater<int>());
 4         int sum=accumulate(arr.begin(), arr.end(), 0);
 5         int min_sum=arr[0],index=1;
 6         while(2*min_sum<sum){
 7             min_sum+=arr[index];
 8             index++;
 9         }
10         return index;
11     }

先把数组降序排一遍,然后遍历求和大于剩下一半的和就可以了

posted @ 2018-01-16 11:02  三人木君  阅读(153)  评论(0编辑  收藏  举报