简单题,略。
class Solution {
public boolean lemonadeChange(int[] bills) {
if(bills[0] != 5) return false;
int five = 0, ten = 0;
for(int i = 0; i < bills.length; ++i){
if(bills[i] == 5){
++five;
}else if(bills[i] == 10){
--five;
++ten;
if(five < 0) return false;
}else{
if(ten > 0 && five > 0){
--ten;
--five;
}else if(five > 2){
five -= 3;
}else{
return false;
}
}
}
return true;
}
}
2.Queue Reconstruction by Height
学会LinkedList的声明和sorting 2D array即可。当身高固定时,k从小到大排。疯狂insert array element即可。
class Solution {
public int[][] reconstructQueue(int[][] people) {
Arrays.sort(people, (a, b) -> {
if (a[0] == b[0]) return a[1] - b[1];
return b[0] - a[0];
});
LinkedList<int[]> q = new LinkedList<>();
for (int[] p : people) {
q.add(p[1],p);
}
return q.toArray(new int[people.length][]);
}
}
bonus: Valid Parenthesis String
值得一看。
class Solution {
public boolean checkValidString(String s) {
int min = 0, max = 0;
for(int i = 0; i < s.length(); ++i){
int tmp = s.charAt(i);
if(tmp == '('){
++min;
++max;
}else if(tmp == ')'){
min = Math.max(min-1, 0);
--max;
}else{
min = Math.max(min-1, 0);
++max;
}
if(max < 0) return false;
}
return min == 0;
}
}
3.Minimum Number of Arrows to Burst Balloons
这 里面写的差值过大问题值得考虑!!!
class Solution {
public int findMinArrowShots(int[][] points) {
Arrays.sort(points, (a, b) -> {
return Integer.compare(a[0], b[0]);
});
int max = points[0][1], min = points[0][0], count = 1;
for(int i = 1; i < points.length; ++i){
if(min <= points[i][1] && points[i][1] < max){
max = points[i][1];
}
if(min < points[i][0] && points[i][0] <= max){
min = points[i][0];
}
if(points[i][0] > max){
++count;
min = points[i][0];
max = points[i][1];
}
}
return count;
}
}
文章包含四个编程挑战的解决方案:1.LemonadeChange关注于5美元和10美元找零;2.QueueReconstructionbyHeight使用排序和链表重建队列;3.ValidParenthesisString检查字符串中括号的有效性;4.MinimumNumberofArrowstoBurstBalloons寻求最少箭数来爆破气球,涉及区间处理和排序。
796

被折叠的 条评论
为什么被折叠?



