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.
/**
* Caterpillar Method
* (s, t) move forward
* O(N) amortized time
*/
bool existed(vector<int> &vec, int target)
{
if(vec.empty()) return false;
int front(0), sum(0);
for(int back(0); back<vec.size(); ++back) {
while(front < vec.size() && sum + vec[front] <= target) {
sum += vec[front];
++ front;
}
if(sum == target) return true;
sum -= vec[back];
}
return false;
}
def caterpillarMethod(A, s):
n = len(A)
front, total = 0, 0
for back in xrange(n):
while (front < n and total + A[front] <= s):
total += A[front]
front += 1
if total == s:
return True
total -= A[back]
return False
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.
int lengthOfLongestSubstring(string str) {
if(str.size() < 2) return str.size();
vector<int> hash(256);
int res(0);
int front(0), back(0);
for(; back<str.size(); ++back) {
while(front < str.size() && hash[str[front]] == 0) {
++hash[str[front]];
++ front;
}
res = max(res, front-back);
--hash[str[back]];
}
return res;
}
具体地说,we have to count the number of triplets at indices x < y < z, such that Ax <= Ay <= Az, 且 Ax +Ay > Az
def triangles(A):
n = len(A)
result = 0
for x in xrange(n):
z = 0
for y in xrange(x + 1, n):
while (z < n and A[x] + A[y] > A[z]):
z += 1
result += z - y - 1
return result