首页 > 试题广场 >

掰花瓣

[编程题]掰花瓣
  • 热度指数:650 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
手上有 n 朵花,每朵的花瓣数保存在一个数组中。我们每次可以选择任意一朵,拿走其中的一瓣或者两瓣,求掰完所有花的最少次数。
示例1

输入

[4,2,1]

输出

4
每朵花的花瓣掰完需要花瓣数除以2向上取整次,加起来就得到了所有花的花瓣掰完的总次数
import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param petals int整型一维数组 花瓣数
     * @return int整型
     */
    public int petalsBreak (int[] petals) {
        // write code here
        int times = 0;
        for(int num: petals) times += (num + 1) / 2;
        return times;
    }
}

编辑于 2021-09-24 13:17:19 回复(0)
关键在于 每次选择其中一朵
import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param petals int整型一维数组 花瓣数
     * @return int整型
     */
    public int petalsBreak (int[] petals) {
        // write code here
        int res = 0;
        for(int petal: petals){
            if(petal % 2 == 0) res += petal/2;
            else res += petal/2 + 1;
        }
        return res;
    }
}

发表于 2021-09-01 23:52:57 回复(0)
感觉应该就是贪心的思想,能够拿两个花瓣就拿两个,仅剩一个的话就只拿一个。
这里用整数除法和取余来统计次数
import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param petals int整型一维数组 花瓣数
     * @return int整型
     */
    public int petalsBreak (int[] petals) {
        // write code here
		
		int ans = 0;
		for (int i = 0; i < petals.length; i++) {
			ans += petals[i] / 2;
			ans += petals[i] % 2;
		}
		return ans;
    }
}


发表于 2022-06-07 14:43:45 回复(0)
每次可以选择任意一朵,所以可以直接遍历petals,即从第一朵开始按顺序拿
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param petals int整型vector 花瓣数
     * @return int整型
     */
    int petalsBreak(vector<int>& petals) {
        int num;
        int temp;
        for(int i=0; i<petals.size(); i++){
            if(petals[i] % 2){  // 不是偶数
                num += (petals[i]+1) / 2;
            }
            else{  // 偶数
                num += petals[i] / 2;
            }
        }
        return num;
    }
};

发表于 2021-12-17 16:28:35 回复(0)
int i=0;
int count=0;
int sum=0;
	while (i < petalsLen)
	{
		if (*petals == 0)
		{
			count = 0;
		}
		else
		{
			count = (*petals + 1) / 2;
		}
		sum = sum + count;
		*(petals++);
		++i;
	}
    return sum;
发表于 2021-09-06 20:10:34 回复(0)