455.分发饼干
leetcode题目链接:https://leetcode.cn/problems/assign-cookies
leetcode AC记录:
代码如下:
public int findContentChildren(int[] g, int[] s) {
Arrays.sort(g);
Arrays.sort(s);
int res = 0;
int sIndex = 0;
int gIndex = 0;
while(gIndex < g.length && sIndex < s.length) {
if(g[gIndex] <= s[sIndex]) {
res++;
gIndex++;
}
sIndex++;
}
return res;
}
376. 摆动序列
leetcode题目链接:https://leetcode.cn/problems/wiggle-subsequence
leetcode AC记录:
代码如下:
//本体可以理解为升降的次数
public int wiggleMaxLength(int[] nums) {
int res = 1;
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
int upOrDown = 2; // 0 降 1 升
for(int i = 1;i <= nums.length -1;i++) {
//下降
if(nums[i-1] > nums[i]) {
//初始值或者之前是上升,子序列长度增加
if(upOrDown == 2 || upOrDown == 1) {
res++;
upOrDown = 0;
}
//上升
} else if(nums[i-1] < nums[i]) {
if(upOrDown == 2 || upOrDown == 0) {
res++;
upOrDown = 1;
}
}
}
return res;
}
53. 最大子序和
leetcode题目链接:https://leetcode.cn/problems/maximum-subarray
leetcode AC记录:
代码如下:
public int maxSubArray(int[] nums) {
int currentSum = nums[0];
int res = currentSum;
for(int i = 1;i < nums.length;i++) {
currentSum = nums[i] > currentSum + nums[i] ? nums[i] : currentSum + nums[i];
res = res > currentSum ? res : currentSum;
}
return res;
}
122.买卖股票的最佳时机II
leetcode题目链接:https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-ii/
leetcode AC记录:
代码如下:
public int maxProfit(int[] prices) {
int res = 0;
for(int i = 1;i <= prices.length - 1;i++) {
if(prices[i-1] < prices[i]) {
res += prices[i] - prices[i-1];
}
}
return res;
}
55. 跳跃游戏
leetcode题目链接:https://leetcode.cn/problems/jump-game
leetcode AC记录:
代码如下:
public boolean canJump(int[] nums) {
int index = 0;
int length = nums.length;
while(index < nums.length) {
if(index >= nums.length -1) {
return true;
} else if(nums[index] == 0) {
return false;
}
int maxIndex = Integer.MIN_VALUE;
for(int i = 1; i <= nums[index]; i++) {
if(nums[index + i] + i + index >= nums.length -1) {
return true;
}
if(maxIndex < 0 || nums[index + i] + i + index > maxIndex + nums[maxIndex]) {
maxIndex = index + i;
}
}
index = maxIndex;
}
return true;
}
45.跳跃游戏II
leetcode题目链接:https://leetcode.cn/problems/jump-game-ii
leetcode AC记录:
代码如下:
public int jump(int[] nums) {
int index = 0;
int length = nums.length;
int res = 0;
while(index < nums.length -1) {
int num = nums[index];
int maxIndex = index;
for(int i = 1;i <= num;i++) {
if(index + i >= nums.length - 1) {
return res + 1;
} else if(nums[index + i] + index + i > nums[maxIndex] + maxIndex) {
maxIndex = index + i;
}
}
index = maxIndex;
res++;
// if(nums[maxIndex] + maxIndex >= nums.length -1) {
// return res+1;
// }
}
return res;
}