643 Maximum Average Subarray I
生活随笔
收集整理的這篇文章主要介紹了
643 Maximum Average Subarray I
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
Easy題的意義是一定要思維縝密。 比如,nums[]有可能是負數(shù),那max的初值就不能是0; 另外,計算完成后total要置0,要么就把total拿到for里面去。
Brute Force
public double findMaxAverage(int[] nums, int k) {double max = Integer.MIN_VALUE;int total = 0;for (int i = 0; i < nums.length + 1 - k; i++) {for (int count = 0; count < k; count++) {total += nums[i + count];}max = Math.max(max, total / (double) k);total = 0 ;}return max;} 復(fù)制代碼Sliding Window
邊界條件最好舉例子帶進去不然會錯。
public double findMaxAverage(int[] nums, int k) {//sliding windowint total = 0;for (int i = 0; i < k; i++) {total += nums[i];}double max = total / (double) k;for (int i = 1; i < nums.length - k + 1; i++) {total = total - nums[i - 1];total = total + nums[i + k - 1];max = Math.max(total / (double) k, max);}return max;} 復(fù)制代碼另外還有種方法: Approach #2 Cumulative Sum [Accepted]
轉(zhuǎn)載于:https://juejin.im/post/5a3134166fb9a0451d417a15
總結(jié)
以上是生活随笔為你收集整理的643 Maximum Average Subarray I的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【CodeForces】576 C. P
- 下一篇: 项目经理面试中可能遇到的问题