LeetCode刷題記錄(第十二天)

2021-08-18 01:22:29 字數 2051 閱讀 5096

原題目:

given an integer array with 

even

length, where different numbers in this array represent different 

kinds

of candies. each number means one candy of the corresponding kind. you need to distribute these candies 

equally

in number to brother and sister. return the maximum number of 

kinds

of candies the sister could gain.

翻譯後:

給定乙個長度為

偶數的整數陣列

,其中陣列

中的不同數字表示不同

種類的糖果。

每個數字表示相應種類的乙個糖果。

你需要將這些糖果

分配給兄弟姐妹。

返回姊妹可以獲得

的最大數量的

糖果種類

。事例:

example 1:

input: candies = [1,1,2,2,3,3]

output: 3

explanation:

there are three different kinds of candies (1, 2 and 3), and two candies for each kind.

optimal distribution: the sister has candies [1,2,3] and the brother has candies [1,2,3], too.

the sister has three different kinds of candies.

example 2:

input: candies = [1,1,2,3]

output: 2

explanation: for example, the sister has candies [2,3] and the brother has candies [1,1].

the sister has two different kinds of candies, the brother has only one kind of candies.

思路:首先,兄弟姐妹們平分這些糖果,所以,姐妹能拿到不同類別最多種類的糖果就只能是n/2種,n是糖果的總數,也就是陣列的長度。

所以我的想法很簡單:1、遍歷陣列,碰到不相同的糖果就放入乙個新的陣列;

2、最後看新陣列的長度與n/2相比較,如果大於等於,則返回n/2,否則返回新陣列的長度。

以下是我寫的**:

package com.mianshi.suanfa.distributecandies;

/** * created by macbook_xu on 2018/4/1.

*/public class solution

}

但是我的**是建立在傳入的陣列為排序後的陣列的,當然,如果是無序的,咱們可以自己排一下,而且我沒定義新的陣列,這麼想只是方便理解。

官方的答案給出了四種方法,下面給大家看兩種簡單明瞭的方法(有兩種方法比較複雜,不太好理解,而且效率並不是很好):

public class solution 

}

這種方法和我的想法是差不多的,先進行排序,他是判斷當前數比前乙個大,和我的判斷不相等是乙個道理。

public class solution 

return math.min(set.size(), candies.length / 2);

}}

這個方法使用了set,看了這個方法,我知道為什麼面試總會問關於集合的問題了,確實在解決問題的使用恰當會非常的方便,利用hashset中元素不可重複,直接就可以求出不同的糖果數目,嘿嘿。

leetcode刷題記錄

我覺得每天來兩道,練習練習,再看看人家是怎麼優化的。1.給定乙個整數陣列 nums 和乙個目標值 target,請你在該陣列中找出和為目標值的那 兩個 整數,並返回他們的陣列下標。c 暴力求解,204ms,9.1m class solution for index,num in enumerate ...

LeetCode刷題記錄

動態規劃和貪心演算法的異同點 class solution throw newruntimeexception 時間複雜度 o n 2 對於每個元素,我們試圖通過遍歷陣列的其餘部分來尋找它所對應的目標元素,這將耗費 o n o n 的時間。因此時間複雜度為 o n 2 需要一種方法,尋找符合要求的元...

leetcode刷題記錄

工作之餘刷刷題排解下寂寞 1 面試題66.構建乘積陣列 解題思路 題目要求可以簡化為求陣列中任意乙個元素左右兩邊所有元素的乘積。偷懶就用了乙個套路,練習了p c c python class solution def constructarr self,a list int list int 除法是...