zoukankan      html  css  js  c++  java
  • 和为s的两个数字 和为s的连续正数序列

    输入一个递增排序的数组和一个数字s,在数组中查找两个数,使得它们的和正好是s,如果有多对数字的和等于s,输出任意一对即可。

    #include <iostream>
    
    using namespace std;
    
    //复杂度为O(n)
    bool findnumber(int data[],int length,int sum,int &num1,int &num2)
    {
        bool found=false;
        if(data==NULL||length<1)
            return found;
        int low=0,high=length-1;
        while(low<high)
        {
            long long cursum=data[low]+data[high];
            if(cursum==sum)
            {
                num1=data[low];
                num2=data[high];
                found=true;
                break;
            }
            else if(cursum<sum)
                low++;
            else
                high--;
        }
        return found;
    
    }
    
    int main()
    {
        int data[5]={1,3,6,8,9};
        int length=5,num1=0,num2=0,sum=1;
        bool found=findnumber(data,length,sum,num1,num2);
        cout<<found<<"  "<<num1<<"  "<<num2;
    }

    输入一个递增排序的数组和一个数字S,在数组中查找两个数,是的他们的和正好是S,如果有多对数字的和等于S,输出两个数的乘积最小的。

    #include <iostream>
    
    using namespace std;
    
    void printnumber(int low,int high)
    {
        for(int i=low;i<=high;i++)
            cout<<i<<" ";
        cout<<'
    ';
    }
    
    void findnumber(int sum)
    {
        if(sum<3)
            return;
        int low=1,high=2,middle=(1+sum)/2,cursum=low+high;
        while(low<middle) //注意low,非high,s=偶数
        {
            if(cursum==sum)
                printnumber(low,high);
            while(cursum>sum&&low<middle)
            {
                cursum-=low;
                low++;
                if(cursum==sum)
                    printnumber(low,high);
            }
            high++;
            cursum+=high;
        }
    }
    
    int main()
    {
        findnumber(9);
    }
  • 相关阅读:
    Python的内置模块itertools
    列表的sort()和sorted()方法
    Python面试
    数据分析相关概念
    数据分析中Numpy,Pandas,Matplotlib,scripy和Scikit-Learn等数据处理库...
    mysql数据库的语法及简介
    Cannot add foreign key constraint
    MySQL数据库重装
    MySQL数据库在Python中的操作
    Python中的取整函数
  • 原文地址:https://www.cnblogs.com/home123/p/7190806.html
Copyright © 2011-2022 走看看