leetcode 贪心算法相关
1.1 分糖果
https://leetcode.com/problems/assign-cookies/
class Solution {
public int findContentChildren(int[] g, int[] s) {
Arrays.sort(g);
Arrays.sort(s);
int child = 0;
int num = 0;
while(child < g.length && num < s.length){
if(g[child] <= s[num]){
child ++;
}
num ++;
}
return child;
}
}
1.2 摇摆序列
https://leetcode.com/problems/wiggle-subsequence/
class Solution {
public int wiggleMaxLength(int[] nums) {
if(nums.length < 2){
return nums.length;
}
int DOWN = -1;
int UP = 1;
int maxLength = 1;
int state = 0;
for(int i = 1;i < nums.length; i ++){
if(i == 1 || state == 0){
if(nums[i-1] < nums[i]){
state = UP;
maxLength ++;
}else if(nums[i-1] > nums[i]){
state = DOWN;
maxLength ++;
}
}else if(state == DOWN){
if(nums[i-1] < nums[i]){
state = UP;
maxLength ++;
}
}else if(state == UP){
if(nums[i-1] > nums[i]){
state = DOWN;
maxLength ++;
}
}
}
return maxLength;
}
}
1.3 移除K个数字
https://leetcode.com/problems/remove-k-digits/
class Solution {
public String removeKdigits(String num, int k) {
if(num == null || num.length() == 0){
return "0";
}
Stack<Character> stack = new Stack<>();
for(int i = 0;i < num.length(); i++){
char c = num.charAt(i);
while(!stack.isEmpty() && k > 0 && stack.peek() > c){
stack.pop();
k --;
}
if(c != '0' || !stack.isEmpty()){
stack.push(c);
}
}
while(k > 0 && !stack.isEmpty()){
stack.pop();
k --;
}
StringBuilder sb = new StringBuilder();
while(!stack.isEmpty()){
sb.append(stack.pop());
}
sb.reverse();
if("".equals(sb.toString())){
return "0";
}
return sb.toString();
}
}