455.分发饼干
学习文章链接: 思路:
满足最小胃口的孩子,遍历饼干,指针自增; 满足最大胃口的孩子,遍历孩子,指针自减; 两种思路均需要排序; 查看代码会发现,不同点只在于互换了角色。 代码:
class Solution {
public int findContentChildren ( int [ ] g, int [ ] s) {
Arrays . sort ( g) ;
Arrays . sort ( s) ;
int res = 0 ;
int index = 0 ;
for ( int i = 0 ; i < s. length; i++ ) {
if ( index <= g. length - 1 && g[ index] <= s[ i] ) {
res++ ;
index++ ;
}
}
return res;
}
}
class Solution {
public int findContentChildren ( int [ ] g, int [ ] s) {
Arrays . sort ( g) ;
Arrays . sort ( s) ;
int res = 0 ;
int index = s. length - 1 ;
for ( int i = g. length - 1 ; i >= 0 ; i-- ) {
if ( index >= 0 && s[ index] >= g[ i] ) {
res++ ;
index-- ;
}
}
return res;
}
}
376. 摆动序列
学习文章链接: 思路:将数组转化为折线图,遇到波峰波谷就进行结果的累计。贪心和动态规划两种思路,仅有一个元素或者含两个不等元素的序列也视作摆动序列。pre=0即为了判断数组最前面两个数是否为摆动数列。 代码:
class Solution {
public int wiggleMaxLength ( int [ ] nums) {
if ( nums. length <= 1 ) return nums. length;
int res = 1 ;
int pre = 0 ;
for ( int i = 1 ; i < nums. length; i++ ) {
if ( ( pre <= 0 && nums[ i] - nums[ i - 1 ] > 0 ) || ( pre >= 0 && nums[ i] - nums[ i - 1 ] < 0 ) ) {
res++ ;
pre = nums[ i] - nums[ i - 1 ] ;
}
}
return res;
}
}
53. 最大子序和
学习文章链接:代码随想录 思路:一旦累加和出现负值,那么累加和赋值零。 代码:
class Solution {
public int maxSubArray ( int [ ] nums) {
int maxRes = Integer . MIN_VALUE ;
int sum = 0 ;
for ( int i = 0 ; i < nums. length; i++ ) {
sum += nums[ i] ;
if ( sum > maxRes) {
maxRes = sum;
}
if ( sum < 0 ) {
sum = 0 ;
}
}
return maxRes;
}
}