- 561. 数组拆分
- 解题思路
- 代码实现
- 1. Python实现
- 2. Java实现
- 605. 种花问题
- 解题思路
- 代码实现
- 1. Python实现
- 2. Java实现
- 明日预告
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,惊了。
明日预告
继续贪婪算法两道简单题,如果自我感觉良好,那就换算法。
- 680验证回文字符串II
- 860柠檬水找零



