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


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

  • 相关阅读:
    POJ 1887 Testing the CATCHER
    HDU 3374 String Problem
    HDU 2609 How many
    POJ 1509 Glass Beads
    POJ 1458 Common Subsequence
    POJ 1159 Palindrome
    POJ 1056 IMMEDIATE DECODABILITY
    POJ 3080 Blue Jeans
    POJ 1200 Crazy Search
    软件体系结构的艺术阅读笔记1
  • 原文地址:https://www.cnblogs.com/Tobyuyu/p/4965605.html
Copyright © 2011-2022 走看看