zoukankan      html  css  js  c++  java
  • 【Data Structure & Algorithm】在排序数组中查找和为定值的两个数

    在排序数组中查找和为定值的两个数


    题目:输入一个已经按升序排序过的数组和一个数字,在数组中查找两个数,使得它们的和正好是输入的那个数字,要求时间复杂度是O(n)。如果有多对数字的和等于输入的数字,输出任意一对即可。

    例如输入数组1, 2, 4,7, 11, 15和数字15。由于4+11=15,因此输出是4和11。

    分析:如果不考虑时间复杂度,最简单想法莫过于先在数组中固定一个数字,再依次判断数组中剩下的n-1个数字与它的和是不是等于输入的数字,但是这种思路的时间复杂度是O(n2)。

           假设现在随便在数组找到两个数,如果它们的和等于输入的数字,那就找到了;如果小于输入数字,则把两个数的和调整大一点,把较小的数字往后面移动一个数字;如果大于输入数字,则把两个数的和调整小一点,把较大的数字往前面移动一个数字;这样它们的和就有可能等于输入的数字了。

           总结起来,最初找到数组的第一个数字和最后一个数字,当两个数字的和大于输入的数字时,把较大的数字往前移动;当两个数字的和小于输入的数字时,把较小的数字往后移动;当然也有可能出现没有等于输入数字的情况,要加以判断。

    代码如下:

    /////////////////////////////////////////////////////////////////
    // Find two numbers with a sum in a sorted array
    // Output: true is found such two numbers, otherwise false
    /////////////////////////////////////////////////////////////////
    bool FindTwoNumbersWithSum
    (
           int data[],              // a sorted array
           unsigned int length,     // the length of thesorted array
           int sum,                 // the sum
           int& num1,               // the first number, output
           int& num2                // the second number, output
    )
    {
           bool found = false;
           if(length < 1)
                  return found;
     
           int ahead = length - 1;
           int behind = 0;
     
           while(ahead > behind)
           {
                  long long curSum = data[ahead] + data[behind];
     
                  // if the sum of two numbers is equal to the input, then found them
                  if(curSum == sum)
                  {
                         num1 = data[behind];
                         num2 = data[ahead];
                         found = true;
                         break;
                  }
                  // if the sum of two numbers is greater than the input, delete the greater number
                  else if(curSum > sum)
                         ahead--;
                  // if the sum of two numbers is less than the input, increase the less number
                  else
                         behind++;
           }
           return found;
    }

  • 相关阅读:
    windows 下安装MongoDB
    vue.js环境在window和linux安装
    python3的hashlib库sha256、pbkdf2_hmac、blake2b基本用法
    Locust 接口性能测试
    PyTestReport自动化报告使用说明
    Google开发者F12工具面板-network详解
    AppScan基础使用
    pip下载速度慢解决方法
    pycharm工具设置py模板
    jmeter实操及性能测试基础知识整理
  • 原文地址:https://www.cnblogs.com/DianaCody/p/5425705.html
Copyright © 2011-2022 走看看