https://codility.com/programmers/lessons/13
Caterpillar method
Caterpillar还挺形象。。。
题目:CountDistinctSlices Count Distinct Slices
int solution(int M, vector<int> &A) { // write your code in C++11 int right = 0; vector<int> buf(M+1, -1); int count = 0; for(int i=0;i<A.size();i++) { while(right<A.size()&&buf[A[right]]==-1) { count+=right-i+1; if(count>1000000000) return 1000000000; buf[A[right]] = right; right++; } if(right==A.size()) break; if(right<A.size()&&buf[A[right]]!=-1) { int newi = buf[A[right]]; while(i<newi) { buf[A[i]]=-1; i++; } buf[A[right]]=-1; } } return count; }
题目:MinAbsSumOfTwo Min abs sum of two
bool cmp(int a,int b) { return abs(a)<abs(b); } int solution(vector<int> &A) { // write your code in C++11 sort(A.begin(),A.end(),cmp); if(A.size()==0) return 0; int res = abs(A[0]*2); for(int i=0;i<A.size()-1;i++) { if(abs(A[i]+A[i+1])<res) res = abs(A[i]+A[i+1]); if(abs(A[i]*2)<res) res = abs(A[i]*2); } return min(res,abs(A[A.size()-1]*2)); }