● 455.分发饼干 Assign Cookies - LeetCode
sort(胃口)
sort(饼干)
int res = 0;
int idex = s.length - 1;
从后往前投喂
一定要先遍历胃口,再遍历饼干
for (i = g.length - 1; i >= 0; i--)
while (idx >= 0 && s[idx] >= g[i])
res++;
idx--;//成功投喂才移动
方法二:
用小饼干投喂,从小到大 Time complexity: O(nlogn) Space complexity: O(logn)
class Solution {
public int findContentChildren(int[] g, int[] s) {
Arrays.sort(g);
Arrays.sort(s);
int res = 0;
int i = 0;
int j = 0;
while (i < g.length && j < s.length) {
if (g[i] <= s[j]) {
res++;
i++;
j++;
} else {
j++;
}
}
return res;
}
}
● 376. 摆动序列 Wiggle Subsequence - LeetCode
nums.size() == 1 return 1;
prediff = 0;
curdiff = 0;
res = 1;
for (int i = 0; i < nums.size(); i++)
curdiff = nums[i + 1] - nums[i];
if( (prediff >= 0 && curdiff < 0) || (prediff <= 0 && curdiff > 0))
res++;
prediff = curdiff;
视频一开始讲解没懂,写完代码懂了。。
class Solution {
public int wiggleMaxLength(int[] nums) {
if (nums.length == 1) return 1;
int preDiff = 0;
int curDiff = 0;
int res = 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) {
res++;
preDiff = curDiff;
}
}
return res;
}
}
Time complexity: O(n) Space complexity: O(1)
● 53. 最大子序和 Maximum Subarray - LeetCode
int res = Integer.MIN_VALUE;
int count = 0;
for (int i = 0; i < nums.size(); i++)
count += nums[i];
if (count > res) res = count;
if (count < 0) count = 0;//连续和变成负数才变成0
return res;
class Solution {
public int maxSubArray(int[] nums) {
int res = Integer.MIN_VALUE;
int count = 0;
for (int i = 0; i < nums.length; i++) {
count += nums[i];
if (count > res) res = count;
if (count <= 0) count = 0;
}
return res;
}
}
Time complexity: O(n) Space complexity: O(1)