目录
前沿:撰写博客的目的是为了再刷时回顾和进一步完善,其次才是以教为学,所以如果有些博客写的较简陋,是为了保持进度不得已而为之,还请大家多多见谅。
预:看到题目后的思路和实现的代码。
见:参考答案展示。
感思:对比答案后的思考,与之前做过的题目是否有关联。
行:
(1)对于没做出来的题目,阅读答案后重新做一遍;
(2)下次做题可以尝试改善的方向;
(3)有助于理解的相关的题目
优先级:做题进度>学习&总结>默写回顾>做题数量
题目回顾
1.K次取反后最大化的数组和
题目链接:1005.K次取反后最大化的数组和
class Solution {
public int largestSumAfterKNegations(int[] nums, int k) {
// 绝对值排序:
Arrays.sort(nums);
int len = nums.length;
int[] asort = new int[len];
int left = 0;
int right = len-1;
int index = right;
if(nums[0] >= 0){
asort = nums;
}else{
while(right >= left){
if(nums[left] > 0 || nums[right] > -nums[left]){
asort[index--] = nums[right--];
}else{
asort[index--] = nums[left++];
}
}
}
int sum = 0;
for(int i = len-1;i > 0;i--){
if(k > 0 && asort[i] < 0){
sum -= asort[i];
k--;
}else{
sum += asort[i];
}
// System.out.println("asort[i]:"+asort[i]+"sum:"+sum);
}
if(k > 0){
if(k % 2 == 1){
sum -= asort[0];
}
else{
sum += asort[0];
}
// System.out.println("sum:"+sum);
}else{
sum += asort[0];
}
return sum;
}
}
2.加油站
题目链接:134. 加油站
class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int curSum = 0;
int totalSum = 0;
int count = 0;
int index = 0;
// 寻找起始点
for(int i = 0;i < gas.length;i++){
curSum += gas[i]-cost[i];
totalSum += gas[i]-cost[i];
if(curSum < 0){
index = i+1;
curSum = 0;
}
}
if(totalSum >= 0){
return index;
}else{
return -1;
}
}
}
3.分发糖果
题目链接:135. 分发糖果
class Solution {
public int candy(int[] ratings) {
int len = ratings.length;
int[] candyGet = new int[len];
candyGet[0] = 1;
int sum = 0;
for(int i = 1;i < len;i++){
if(ratings[i] > ratings[i-1]){
candyGet[i] = candyGet[i-1]+1;
}else{
candyGet[i] = 1;
}
// System.out.println("candyGet["+i+"]:"+candyGet[i]);
}
sum = candyGet[len-1];
for(int j = len-2;j >= 0;j--){
// System.out.println("sum:"+sum+",candyGet["+(j+1)+"]:"+candyGet[j+1]);
if(ratings[j] > ratings[j+1]){
candyGet[j] = Math.max(candyGet[j],candyGet[j+1]+1);
}
sum += candyGet[j];
}
return sum;
}
}