一、分发饼干
力扣第455题
代码如下:
class Solution {
public int findContentChildren(int[] g, int[] s) {
int count = 0;
int i = 0;
int j = 0;
Arrays.sort(g);
Arrays.sort(s);
while(i < g.length && j < s.length) {
if(s[j] >= g[i]) {
count ++;
i++;
}
j++;
}
return count;
}
}
时间复杂度:O(nlogn) 和排序有关
空间复杂度:O(1)
二、摆动序列
力扣第376题
注意:把每个元素当成折点,该点前后的折线增减关系用变量记录;
三种情况的考虑:
1. 上下坡中有平坡
2. 数组的首尾两端
3. 单调坡中有平坡
代码如下:
class Solution {
public int wiggleMaxLength(int[] nums) {
if(nums.length <= 1) return nums.length;
int prediff = 0; //前一对差值
int curdiff = 0; //当前一对差值
int count = 1; //记录峰值,最右边默认一个峰值
for(int i = 0; i < nums.length - 1; i++) {
curdiff = nums[i + 1] - nums[i];
if(prediff >= 0 && curdiff < 0 || prediff <= 0 && curdiff > 0) {
count++;
prediff = curdiff;
}
}
return count;
}
}
时间复杂度:O(n);
空间复杂度:O(1);
三、最大子数组和
力扣第53题
难点:
只要连续和还是正数就会对后面的元素起到增大总和的作用。 所以只要连续和为正数我们就保留。
代码如下:
class Solution {
public int maxSubArray(int[] nums) {
int result = Integer.MIN_VALUE;
int count = 0;
for(int i = 0; i < nums.length; i++) {
count += nums[i];
if(count > result) {
result = count;
}
if(count < 0) count = 0;
}
return result;
}
}
时间复杂度:O(n)
空间复杂度:O(1)