第一题Leetcode135题 分发糖果
这个题,之前某次笔试的时候遇到过,当时自己是想遍历一次找到结果,结果没有通过全部案例,后面检查的时候也没找出问题;
这次的思路,因为要求比左右边的大,可以遍历两次,左边遍历一次,右边遍历一次,然后取两者的最大值! 和某个leetcode的题目真的很像,待会找找
class Solution { public int candy(int[] ratings) { int n = ratings.length; int[] left = new int[n]; int[] right = new int[n]; Arrays.fill(left,1); Arrays.fill(right,1); for(int i = 1;i < n;i++){ if(ratings[i] > ratings[i - 1]){ left[i] = left[i - 1] + 1; } } for(int i = n - 2;i >= 0;i--){ if(ratings[i] > ratings[i + 1]){ right[i] = right[i + 1] + 1; } } int res = 0; for(int i = 0;i < n;i++){ left[i] = Math.max(left[i],right[i]); res += left[i]; } return res; }}
第二题 338题比特位计数
很巧妙
class Solution {
public int[] countBits(int num) {
int[] res = new int[num + 1];
for (int i = 1;i <= num;i++){
res[i] = res[i & (i - 1)] + 1;
}
return res;
}
}