2020-6-7
If 10% of the profits,capital will ensure being used everywhere;
20% of the profits,capital can active;
50% of the profits,capital will rush into danger。
for 100% of the profits,capital would dare to trample all human laws;
there are more than 300% of the profits,capital would dare to commit any crimes,and even go to the first to take the risk of strangulation。
如果有10%的利潤,資本就會保證到處被使用;
有20%的利潤,資本就能活躍起來;
有50%的利潤,資本就會鋌而走險;
爲了100%的利潤,資本就敢踐踏一切人間法律;
有300%以上的利潤,資本就敢犯任何罪行,甚至去冒絞首的危險。
馬克思 --《資本論》
題目 :
leetcode – 1431. 擁有最多糖果的孩子
給你一個數組 candies 和一個整數 extraCandies ,其中 candies[ i] 代表第 i 個孩子擁有的糖果數目。
對每一個孩子,檢查是否存在一種方案,將額外的 extraCandies 個糖果分配給孩子們之後,此孩子有 最多 的糖果。注意,允許有多個孩子同時擁有 最多 的糖果數目。
示例 1:
輸入:candies = [ 2,3,5,1,3] , extraCandies = 3
輸出:[ true,true,true,false,true]
解釋:
孩子 1 有 2 個糖果,如果他得到所有額外的糖果(3個),那麼他總共有 5 個糖果,他將成爲擁有最多糖果的孩子。
孩子 2 有 3 個糖果,如果他得到至少 2 個額外糖果,那麼他將成爲擁有最多糖果的孩子。
孩子 3 有 5 個糖果,他已經是擁有最多糖果的孩子。
孩子 4 有 1 個糖果,即使他得到所有額外的糖果,他也只有 4 個糖果,無法成爲擁有糖果最多的孩子。
孩子 5 有 3 個糖果,如果他得到至少 2 個額外糖果,那麼他將成爲擁有最多糖果的孩子。
示例 2:
輸入:candies = [ 4,2,1,1,2] , extraCandies = 1
輸出:[ true,false,false,false,false]
解釋:只有 1 個額外糖果,所以不管額外糖果給誰,只有孩子 1 可以成爲擁有糖果最多的孩子。
示例 3:
輸入:candies = [ 12,1,12] , extraCandies = 10
輸出:[ true,false,true]
提示:
2 <= candies.length <= 100
1 <= candies[ i] <= 100
1 <= extraCandies <= 50
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/kids-with-the-greatest-number-of-candies
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
個人解答:(C版本)
先找到未分配前單個孩子擁有糖果數量的最大值,然後逐個讓每個孩子的糖果數量加上額外提供的數量與那個最大值作比較,大於等於爲真,小於爲假。
bool* kidsWithCandies ( int * candies, int candiesSize, int extraCandies, int * returnSize) {
if ( candies == NULL || candiesSize<= 0 )
return NULL ;
bool* ret = ( bool* ) malloc ( candiesSize* sizeof ( bool) ) ;
int max = 0 ;
for ( int i= 0 ; i< candiesSize; ++ i)
{
if ( candies[ i] > max)
{
max = candies[ i] ;
}
}
for ( int i= 0 ; i< candiesSize; ++ i)
{
if ( candies[ i] + extraCandies >= max)
{
ret[ i] = true;
}
else
{
ret[ i] = false;
}
}
* returnSize = candiesSize;
return ret;
}
複雜度分析
1)時間複雜度:一遍查找,一遍比較,O(N)。
2)空間複雜度:由於要申請n個空間來存儲結果,所以爲O(N)。
運行結果:
他山之石: