分发饼干 LeetCode 51
题目链接:[LeetCode 51 - 简单]
思路
主要解决方式:使用胃口值取去寻找饼干的尺寸
贪心:
class Solution {
public int findContentChildren(int[] g, int[] s) {
int result = 0;
if(g.length==0||s.length==0)return result;
Arrays.sort(g);
Arrays.sort(s);
int index = 0;
for(int i=0;index<g.length&&i<s.length;i++){
if(g[index]<=s[i]){
result++;
index++;
}
}
return result;
}
}
K 次取反后最大化的数组和 LeetCode 1005
题目链接:[LeetCode 1005 - 简单]
思路
将nums数组根据绝对值大小,从大到小排列
nums = IntStream.of(nums)
.boxed()
.sorted((o1,o2)->Math.abs(o2)-Math.abs(o1))
.mapToInt(Integer::intValue).toArray();
最后根据剩余k是否能被2整除来决定最后一个最小值是否为负
if(k%2 == 1)nums[len-1]=-nums[len-1];
使用Arrays对数组进行加法运算:
Arrays.stream(nums).sum();
贪心:
class Solution {
public int largestSumAfterKNegations(int[] nums, int k) {
nums = IntStream.of(nums)
.boxed()
.sorted((o1,o2)->Math.abs(o2)-Math.abs(o1))
.mapToInt(Integer::intValue).toArray();
int len = nums.length;
for(int i=0;i<len;i++){
if(nums[i]<0 && k>0){
nums[i]=-nums[i];
k--;
}
}
if(k%2 == 1)nums[len-1]=-nums[len-1];
return Arrays.stream(nums).sum();
}
}
柠檬水找零 LeetCode 860
题目链接:[LeetCode 860 - 简单]
思路
思路不难
贪心:
class Solution {
public boolean lemonadeChange(int[] bills) {
int five = 0;
int ten = 0;
for(int i=0;i<bills.length;i++){
if(bills[i]==5){
five++;
}else if(bills[i]==10){
if(five >= 1){
five--;
ten++;
}else{
return false;
}
}else if(bills[i]==20){
if(five >= 1 && ten >=1 ){
five--;
ten--;
}else if(five >= 3){
five-=3;
}else{
return false;
}
}
}
return true;
}
}