1. 求滑动(移动)平均(moving average)

double partialSum = 0;
for (int i = 0; i < M-1; ++i)
    partialSum += A[i];

for (int i = M-1; i < N; ++i){
    partialSum += A[i];
    ret.push_back(partialSum/3);
    partialSum -= A[i+1-M];
}

2. 从中间向左右

int mid = (lo + hi)/2;
int left = MIN, right = MIN;
int sum = 0;

for (int i = mid; i >= lo; --i)
    left = max(left, sum += A[i]);

sum = 0;
for (int i = mid+1; i <= high; ++i) 
    right = max(right, sum += A[i]);

int across = left + right;

3. 从中间向两边的方式之二

int i = mid, j = mid+1;
while (i > lo || j < hi){
    if (i > lo && (j == hi || h[i-1] > h[j+1])) {
        --i;
        ...
    } else {
        ++j;
    }
}

4. 均分两段,分别遍历

int len = pow(2, k);
for (int i = 0, j = len/2; i < len/2 && j < len; ++i, ++j){
    ...
}

5. 固定起点、设置偏移(skip 或叫 offset)

for (int skip = 0; s + skip < S.size(); ++skip){
    ...             // 这样 skip 表示的是对 s 的相对位置;
}
posted on 2016-09-04 09:23  未雨愁眸  阅读(351)  评论(0编辑  收藏  举报