Smallest Subset-LintCode

204 篇文章 0 订阅

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

#ifndef C761_H
#define C761_H
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class Solution {
public:
    /**
    * @param nums: an array of non-negative integers
    * @return: minimum number of elements
    */
    int minElements(vector<int> &nums) {
        // write your code here
        if (nums.empty())
            return 0;
        int sum = 0;
        int cnt = 0;
        sort(nums.begin(),nums.end());//排序数组
        for (auto c : nums)//计算nums所有元素的和
            sum += c;
        sum = sum / 2 + 1;//取元素之和的一半
        for (int i = nums.size() - 1; i >= 0; --i)
        {
            sum -= nums[i];
            cnt++;
            if (sum <= 0)//若此时取过的数组已经大于元素之和的一般,返回cnt
            {
                return cnt;
            }
        }
    }
};
#endif
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值