Greedy Algorithm EASY 21.11.06


561. 数组拆分


[题目说明](561. 数组拆分 I - 力扣(LeetCode) (leetcode-cn.com))


解题思路

四个字:门当户对。大的两个数配一对,小的两个数配一对。注意是简单题啊,题目规定好了数组长度为2n。


代码实现


1. Python实现
class Solution(object):
    def arrayPairSum(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        nums.sort()
        n = 0
        res = 0
        while n < len(nums):
            res = res + nums[n]
            n = n + 2
        return res

2. Java实现
  • 我作弊写的
class Solution {
    public int arrayPairSum(int[] nums) {
        Arrays.sort(nums);
        int ans = 0;
        int n = 0;
        while (n < nums.length){
            ans = ans + nums[n];
            n += 2;
        }
        return ans;
    }
}
  • 官方写法
class Solution {
    public int arrayPairSum(int[] nums) {
        Arrays.sort(nums);
        int ans = 0;
        for (int i=0; i < nums.length; i += 2){
            ans += nums[i];
        }
        return ans;
    }
}
  • 新学Java方法
//对数组排序
Arrays.sort(nums);
//求数组长度
nums.length;

605. 种花问题


[题目说明](605. 种花问题 - 力扣(LeetCode) (leetcode-cn.com))


解题思路

四个字:见缝插针。对数组做遍历,加些判断,如果有缝就插一个。


代码实现

1. Python实现
class Solution(object):
    def canPlaceFlowers(self, flowerbed, n):
        """
        :type flowerbed: List[int]
        :type n: int
        :rtype: bool
        """
        index = 0
        res = 0
        while index < len(flowerbed):
            if flowerbed[index]:
                index += 2
            elif index != len(flowerbed) - 1:
                if flowerbed[index + 1]:
                    index += 1
                else:
                    res = res + 1
                    index = index + 2
            else:
                res = res + 1
                index = index + 1
        return res >= n

2. Java实现
class Solution {
    public boolean canPlaceFlowers(int[] flowerbed, int n) {
        int index = 0;
        int ans = 0;
        while (index < flowerbed.length){
            if (flowerbed[index] == 1){
                index += 2;
            }else if (index != flowerbed.length - 1){
                if (flowerbed[index + 1] == 1){
                    index += 1;
                }else {
                    index = index + 2;
                    ans = ans + 1;
                }
            }else{
                ans += 1;
                index = index + 1;
            }
        }
        return ans >= n;
    }
}

执行时间1ms,惊了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值