12月21日
746.使用最小花费爬楼梯
//动态规划
class Solution {
public int minCostClimbingStairs(int[] cost) {
if(cost.length == 2) {
return cost[0] > cost[1] ? cost[1] : cost[0];
}
for(int i = 2; i < cost.length; i ++) {
cost[i] = Math.min(cost[i-1] + cost[i], cost[i-2] + cost[i]);
}
return Math.min(cost[cost.length - 1], cost[cost.length - 2]);
}
}
12月22日
103.二叉树的锯齿形层序遍历
//深度优先搜索
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> res = new LinkedList<>();
traversal(root, res, 0);
return res;
}
public void traversal(TreeNode root, List<List<Integer>> res, int level) {
if(root == null) {
return ;
}
//如果该层有值,则先添加该层
if(res.size() == level) {
res.add(new LinkedList<Integer>());
}
//判断是从右到左输入,还是从左到右输入
if(level % 2 == 1) {
res.get(level).add(0, root.val);
} else {
res.get(level).add(root.val);
}
traversal(root.left, res, level + 1);
traversal(root.right, res, level + 1);
}
}
//广度优先搜索
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> res = new LinkedList<>();
if(root == null) {
return res;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
Boolean leftToRight = true;
while(!queue.isEmpty()) {
int sum = queue.size();
List<Integer> level = new LinkedList<>();
for(int i = 0; i < sum; i ++) {
TreeNode node = queue.poll();
if(leftToRight) {
level.add(node.val);
} else {
level.add(0, node.val);
}
if(node.left != null) {
queue.add(node.left);
}
if(node.right != null) {
queue.add(node.right);
}
}
res.add(level);
leftToRight = !leftToRight;
}
return res;
}
}
12月23日
387.字符串中的第一个唯一字符
class Solution {
public int firstUniqChar(String s) {
int[] frequency = new int[26];
char[] c = s.toCharArray();
for(int i = 0; i < c.length; i ++) {
frequency[c[i] - 'a'] ++;
}
for(int i = 0; i < c.length; i ++) {
if(frequency[c[i] - 'a'] == 1) {
return i;
}
}
return -1;
}
}
class Solution {
public int firstUniqChar(String s) {
for(int i = 0; i < s.length(); i ++) {
char ch = s.charAt(i);
//public int lastIndexOf(int ch): 返回指定字符在此字符串中最后一次出现处的索引,如果此字符串中没有这样的字符,则返回-1
if(s.indexOf(ch) == s.lastIndexOf(ch)) {
return i;
}
}
return -1;
}
}
11月24日
135.分发糖果
class Solution {
public int candy(int[] ratings) {
int[] num = new int[ratings.length];
for(int i = 0; i < ratings.length; i ++){
num[i] = 1;
}
// 每个孩子跟他左边孩子比较,如果他比左边孩子表现好,他就比左边孩子多一个糖果
for(int i = 1; i < ratings.length; i ++) {
if(ratings[i-1] < ratings[i]) {
num[i] = num[i-1] + 1;
}
}
// 每个孩子和他右边孩子比较,如果他比右边孩子表现好,他就比右边孩子多一个糖果
// 但这时需要注意,如果他本身的糖果数多于右边孩子,则就不需要重新赋值
for(int i = ratings.length-1; i > 0; i --) {
if(ratings[i-1] > ratings[i]) {
if(num[i-1] < num[i] + 1) {
num[i-1] = num[i] + 1;
}
}
}
// 统计需要多少糖果
int candys = 0;
for(int i = 0; i < ratings.length; i ++) {
candys += num[i];
}
return candys;
}
}