LeetCode - 575. Distribute Candies
题目链接地址:
https://leetcode.com/problems/distribute-candies/description/
题目大意:
给定一个偶数长度的整数数组,数组中的不同数字代表不同种类的糖果。每一个数字意味着相应的一个糖果。你需要把这些糖果均匀地分配给弟弟和妹妹。返回姐姐能得到的糖果的最大数量。
样例1
输入:糖果= [ 1,1,2,2,3,3 ]
输出:3
解释:
有三种不同的糖果(1, 2和3),每种糖果两种。
优化配置:姐姐有糖果[1,2,3],弟弟有糖果[1,2,3],也。
姐姐有三种不同的糖果。
样例2
输入:糖果= [ 1,1,2,3 ]
输出:2
说明:例如,妹妹有糖果(2,3),而兄弟有糖果(1,1)。
姐姐有两种不同的糖果,弟弟只有一种糖果。
算法思路
第一种:先对数组排序,那么同种糖果归类到了一起。只需遍历数组,每种糖果取一种,直到数量达到一半。
第二种:直接将每种糖果存入set,则可获得所有糖果的种类,若种类大于一半,则返回数组长度的一半(因为妹妹最多获得一半数量糖果)
java代码实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | class Solution { public int distributeCandies( int [] candies) { Set<Integer> kinds = new HashSet<>(); for ( int candy : candies) kinds.add(candy); return kinds.size() >= candies.length / 2 ? candies.length / 2 : kinds.size(); } } public class MainClass { public static int [] stringToIntegerArray(String input) { input = input.trim(); input = input.substring( 1 , input.length() - 1 ); if (input.length() == 0 ) { return new int [ 0 ]; } String[] parts = input.split( "," ); int [] output = new int [parts.length]; for ( int index = 0 ; index < parts.length; index++) { String part = parts[index].trim(); output[index] = Integer.parseInt(part); } return output; } public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader( new InputStreamReader(System.in)); String line; while ((line = in.readLine()) != null ) { int [] candies = stringToIntegerArray(line); int ret = new Solution().distributeCandies(candies); String out = String.valueOf(ret); System.out.print(out); } } } |
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步