一文讲完滑动窗口及经典题目
B1n_
LeetCode643子数组平均最大数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| public double findMaxAverage(int[] nums, int k) { int len = nums.length; int sum = 0; if (k > len || len < 1 || k < 1) { return 0; } for (int i = 0; i < k; i++) { sum += nums[i]; } int res = sum; for (int right = k; right < len; right++) { res = Math.max(res, sum += nums[right] - nums[right - k]); } return (double) res / k; }
|
LeetCode674最长连续递增数列
错误例子:忽视了可能接下来还有连续递增数列
重点:如果右侧元素比左侧元素小,需要重新记录
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| public static void main(String[] args) { int[] nums = {1,3,5,4,7};
int lengthOfLCIS = findLengthOfLCIS(nums); System.out.println(lengthOfLCIS); } public static int findLengthOfLCIS(int[] nums) { int left = 0; int right = 1; int res = 1; int count = 1; while (right < nums.length) { if (nums[left] < nums[right]) { count++; } left++; right++; res = Math.max(res, count); } return res; }
|