zoukankan      html  css  js  c++  java
  • 阿里在线笔试求最接近sum值的最快平均时间复杂度

    给定一个整数sum,从有N个有序元素的数组中寻找元素a、b,使得 a+b 的结果最接近sum,最快的平均时间复杂度是O(N)。

    实现代码如下:

    #include <cstdio>
    #include <iostream>
    #include <cstring>
    #include <cmath>
    #include <string>
    #include <cstdlib>
    #include <algorithm>
    #include <map>
    #include <set>
    #include <utility>
    #include <vector>
    #include <queue>
    
    using namespace std;
    
    #define ll long long
    
    const int N=100005;
    const int A=100000;
    
    ll a,b;  //目标值
    ll x[N];
    ll sum;
    ll n;
    
    int main()
    {
      // freopen("data.in","r",stdin);
        scanf("%I64d%I64d",&n,&sum);
        a=1;b=n;
        ll i,j;
        for(i=1;i<=n;i++){
            scanf("%I64d",&x[i]);
        }
        i=1;j=n;
        a=x[1];b=x[n];
        ll anssum=x[1]+x[n]-sum;
        if(anssum<0) 
            anssum=-anssum;
        ll te;
        while(i<j)  //这里不能i<=j,谨记
        {
            if(x[i]+x[j]==sum)
            {
                a=x[i];
                b=x[j];
                break;
            }
            else if(x[i]+x[j]>sum)
            {
                j--;
            }
            else
            {
                te=x[i]+x[j]-sum;
                if(te<0) te=-te;
                if(te<anssum)
                {
                    anssum=te;
                    a=x[i];b=x[j];
                }
                if(j!=n)
                {
                    te=x[i]+x[j+1]-sum;
                    if(te<0) te=-te;
                    if(te<anssum)
                    {
                        anssum=te;
                        a=x[i];b=x[j+1];
                    }
                }
                i++;
            }
        }
        printf("a=%I64d b=%I64d
    ",a,b);
        return 0;
    }
    


    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    [转]MyBatis传入多个参数的问题
    【转】赶集网mysql开发36军规
    C#套接字和windowsAPI套接字
    java中的注解
    java中的枚举类型
    过去的汇编代码
    近日错误集锦
    java swing模仿随机频谱
    java泛型中的对象
    XML-RPC远程方法调用
  • 原文地址:https://www.cnblogs.com/Tobyuyu/p/4965605.html
Copyright © 2011-2022 走看看