codility _ count distinct slices _ min abs sum of two

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));
}

转载于:https://www.cnblogs.com/parapax/p/3861582.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值