分发饼干(LeetCode 455)
/**
* g 胃口
* s 饼干尺寸
* @param g
* @param s
* @return
*/
public static int findContentChildren(int[] g, int[] s) {
Arrays.sort(g);
Arrays.sort(s);
int count = 0;
int start = s.length - 1;
// 遍历孩子的胃口
for (int i = g.length - 1; i >= 0; i--) {
if (start >= 0 && s[start] >= g[i]) {
start--;
count++;
}
}
return count;
}
柠檬水找零(LeetCode 860)
/**
* 如果第一个就大于5 直接false
* 找钱时优先找大数额的钱,因为最大额度为20,所以找零只有10和5
* @param bills
* @return
*/
public static boolean lemonadeChange(int[] bills) {
if (bills[0] > 5) {
return false;
}
int cash_5 = 5;
int cash_10 = 10;
int num_5 = 1;
int num_10 = 0;
int n = bills.length;
for (int i = 1; i < n; i++) {
if (bills[i] == cash_5) {
num_5++;
}
else if( bills[i] == cash_10 ) {
num_10++;
if (num_5 > 0) {
num_5--;
} else {
return false;
}
} else {
if (num_10 > 0 && num_5 > 0) {
num_5--;
num_10--;
} else if (num_5 >= 3) {
num_5 -= 3;
} else {
return false;
}
}
}
return true;
}