zoukankan      html  css  js  c++  java
  • 阿里在线笔试题 折半方法求最接近sum值

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

    实现代码链接:http://blog.csdn.net/wyh7280/article/details/44941289

    下面给出时间复杂度为O(NlogN)的,采用折半方法搜索最接近的值~

    代码如下:

    #include<iostream>
    #include<stdlib.h>
    #include<stdio.h>
    using namespace std;
    const int N=20;  //该程序中给定了数组长度和数组里面的有序变量,需要修改也很简单,请自行进行
    int array[N]={1,3,5,7,9,12,24,56,78,90,100,120,123,134,156,189,200,201,202,204};
    int search(int targetNum)  //折半查找函数
    {
        int left = 0, right = N-1;
        while(left<=right)
        {
            int midIndex =(right+left)/2;
            int mid=right-left;
            int midValue =array[midIndex];
            if (targetNum == midValue)
            {
                return midIndex;
            }
            else if (targetNum > midValue)
            {
                left = midIndex;
            }
            else
            {
                right = midIndex;
            }
            if(mid<=1)
            {
                break;
            }
        }
    }
    int main(void)
    {
        int sum;
        while(scanf("%d",&sum)==1)
        {
          int a=array[0],b=array[N-1],temp=array[0]+array[N-1]-sum;
          if(array[0]+array[0]>=sum)
          {
              continue;
          }
          if(temp<0)
              temp=-temp;
          for(int i=0;i<N;i++)
          {
             int bb=search(sum-array[i]);
             int te=array[i]+array[bb]-sum;
             if(te<0) te=-te;
             if(te==0)
             {
                 a=array[i];
                 b=array[bb];
                 break;
             }
             if(te<temp&&bb!=i)
             {
                temp=te;
                a=array[i];
                b=array[bb];
             }
          }
          if(a<b)
            cout<<a<<" "<<b<<endl;
          if(a>b)
            cout<<b<<" "<<a<<endl;
        }
        return 0;
    }

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

  • 相关阅读:
    Single Number II
    Pascal's Triangle
    Remove Duplicates from Sorted Array
    Populating Next Right Pointers in Each Node
    Minimum Depth of Binary Tree
    Unique Paths
    Sort Colors
    Swap Nodes in Pairs
    Merge Two Sorted Lists
    Climbing Stairs
  • 原文地址:https://www.cnblogs.com/Tobyuyu/p/4965601.html
Copyright © 2011-2022 走看看