尺取法

问题

尺取法_第1张图片

方法的思想

The idea is to check elements in a way that’s reminiscent of movements of a caterpillar.
The caterpillar crawls through the array. We remember the front and back positions of the
caterpillar, and at every step either of them is moved forward.

分析

基本思想就是让 catepillar 表示 和不大于 s 的连续子数组
Each position of the caterpillar will represent a different contiguous subsequence in which
the total of the elements is not greater than s. Let’s initially set the caterpillar on the first
element. Next we will perform the following steps:

  • if we can, we move the right end (front) forward and increase the size of the caterpillar;
  • otherwise, we move the left end (back) forward and decrease the size of the caterpillar.

In this way, for every position of the left end we know the longest caterpillar that covers
elements whose total is not greater than s. If there is a subsequence whose total of elements
equals s, then there certainly is a moment when the caterpillar covers all its elements.

代码

  
  
  
  
  1. /**
  2. * Caterpillar Method
  3. * (s, t) move forward
  4. * O(N) amortized time
  5. */
  6. bool existed(vector<int> &vec, int target)
  7. {
  8. if(vec.empty()) return false;
  9. int front(0), sum(0);
  10. for(int back(0); back<vec.size(); ++back) {
  11. while(front < vec.size() && sum + vec[front] <= target) {
  12. sum += vec[front];
  13. ++ front;
  14. }
  15. if(sum == target) return true;
  16. sum -= vec[back];
  17. }
  18. return false;
  19. }
  
  
  
  
  1. def caterpillarMethod(A, s):
  2. n = len(A)
  3. front, total = 0, 0
  4. for back in xrange(n):
  5. while (front < n and total + A[front] <= s):
  6. total += A[front]
  7. front += 1
  8. if total == s:
  9. return True
  10. total -= A[back]
  11. return False

类似的题目

Minimum window substring

Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

  
  
  
  
  1. int lengthOfLongestSubstring(string str) {
  2. if(str.size() < 2) return str.size();
  3. vector<int> hash(256);
  4. int res(0);
  5. int front(0), back(0);
  6. for(; back<str.size(); ++back) {
  7. while(front < str.size() && hash[str[front]] == 0) {
  8. ++hash[str[front]];
  9. ++ front;
  10. }
  11. res = max(res, front-back);
  12. --hash[str[back]];
  13. }
  14. return res;
  15. }

有 n 根棍子,计算能够组成的三角形的数目(棍子可以重用)。

具体地说,we have to count the number of triplets at indices x < y < z, such that Ax <= Ay <= Az, 且 Ax +Ay > Az

  
  
  
  
  1. def triangles(A):
  2. n = len(A)
  3. result = 0
  4. for x in xrange(n):
  5. z = 0
  6. for y in xrange(x + 1, n):
  7. while (z < n and A[x] + A[y] > A[z]):
  8. z += 1
  9. result += z - y - 1
  10. return result

更多题目见 codility training center

你可能感兴趣的:(尺取法)