zoukankan      html  css  js  c++  java
  • 计蒜客 两数之和

    两数之和

     

    给定一个数组,找到两个数,使得他们的和为一个给定的数值target。

    函数twoSum返回两个数字index1,index2,

    其中:number[index1] + number[index2]==target;

    注意:index1必须小于index2且不能为0假设每一组输入只有唯一的一组解。

    格式:第一行输入一个数n,接下来的两行分别输入数组number[n]和target,返回index1和index2.

    例如:

    Input:

    numbers={2, 7, 11, 15},

    target=9

    Output:

    index1=1, index2=2

    提示:vector twoSum(vector &number, int target)

    样例输入

    3
    5 75 25
    100

    样例输出

    2 3

     1 #include"iostream"
     2 #include"algorithm"
     3 #define MAX 10000
     4 using namespace std;
     5 
     6 int a[MAX];
     7 int n, tag;
     8 
     9 void twoSum(int n, int *a)
    10 {
    11     for (int i = 0,j=n-1; i<j;)
    12     {
    13         
    14         if (a[i] + a[j] == tag)
    15             {
    16                 cout << i + 1 << " " << j + 1;
    17                 break;
    18             }
    19                 
    20             else if (a[i] + a[j] > tag)
    21                 j--;
    22             else
    23                 i++;
    24         
    25     }
    26 }
    27 
    28 int main()
    29 {
    30 
    31     tag = 0;
    32     cin >> n;
    33     for (int i = 0; i<n; i++)
    34     {
    35         cin >> a[i];
    36     }
    37     cin >> tag;
    38 
    39     sort(a, a + n);
    40     twoSum(n, a);
    41 
    42 }    
  • 相关阅读:
    css盒子模型之内边距padding及简写
    css盒子模型之宽度和高度
    windows 组策略
    windows 快捷键
    cmd 命令快捷键
    django 远程访问
    django 部署在 apache2 上面
    国内常用开源镜像站
    ubuntu1804自带官方源
    ubuntu1604 apt华为国内源
  • 原文地址:https://www.cnblogs.com/SeekHit/p/5552617.html
Copyright © 2011-2022 走看看