Day31 贪心算法
我的思路:
小孩数组g指针一直前移,只有饼干数组s满足条件时,才前移,并且更新num
解答:
java
class Solution {
public int findContentChildren(int[] g, int[] s) {
Arrays.sort(g);
Arrays.sort(s);
int num = 0;
for(int i = g.length - 1, j = s.length - 1; i >= 0 && j >= 0; i--) {
if(g[i] <= s[j]) {
num += 1;
j --;
}
}
return num;
}
}
我的思路:
将数组分为length<2和>=2考虑;
=2时,先判断前两个是否为摆动,是则初始化count = 2,否则初始化count = 1;然后从i = 2,(第三个数字)开始统计count
<2的话,直接返回数组长度length
解答:
java
class Solution {
public int wiggleMaxLength(int[] nums) {
if(nums.length < 2) {
return nums.length;
}
int count = 1;
int prediff = nums[1] - nums[0];
if(prediff != 0) {
count = 2;
}
for(int i = 2; i < nums.length; i++) {
int diff = nums[i] - nums[i-1];
if((diff > 0 && prediff <= 0) || (diff < 0 && prediff >= 0)) {
count ++;
prediff = diff;
}
}
return count;
}
}
我的思路:
用一个同样大小的数组存储遍历到目前的最大连续数组之和,如果遍历到的元素大于之前的数组之和,则进行更新
解答:
java
class Solution {
public int maxSubArray(int[] nums) {
if(nums == null || nums.length == 0) {
return 0;
}
int[] res = new int[nums.length];
res[0] = nums[0];
int maxnum = res[0];
for(int i = 1; i < nums.length; i++) {
res[i] = Math.max(res[i-1] + nums[i], nums[i]);
maxnum = Math.max(res[i], maxnum);
}
return maxnum;
}
}