当前位置:   article > 正文

【LeetCode刷题】1.两数之和

【LeetCode刷题】1.两数之和

一、问题描述

给定一个整数数组nums和一个整数目标值target,请你在该数组中找出和为目标值target的那两个整数,并返回它们的数组下标。你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。你可以按任意顺序返回答案。

示例 1:
输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。

示例 2:
输入:nums = [3,2,4], target = 6
输出:[1,2]

题目来源:力扣(LeetCode)

二、代码过程

#include <iostream>
#include <string>
using namespace std;
void fun(int * nums,int target)//参数为数组nums和目标值target
//【学习】数组传参可以用 * 数组名
{
    int tag = 0;//控制输出
    int length = sizeof(nums);
    //【学习】求数组的长度调用sizeof(nums)
    for(int i = 0;i < length-1;i++)
    {
        for(int j = i+1;j<length;j++)
        {
            if(nums[i]+nums[j]==target)//是否满足条件nums[i]+nums[j]==target
            {
                if(tag == 0)
                {
                    cout<<"------输出------"<<endl;
                    tag = 1;
                }
                cout<<"【"<<i<<","<<j<<"】"<<endl;//若满足输出结果
            }
        }
    }

}
int main(){
    int target;
    const int N = 5;
    int nums[N]={};
    cout<<"------输入------"<<endl;
    cout<<"nums = ";
    for(int i = 0;i<N;i++){
        cin>>nums[i];//输入数组
    }
    cout<<"target = ";
    cin>>target;//输入target
    fun(nums,target);
    return 0;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40

三、运行结果

在这里插入图片描述
在这里插入图片描述

四、学习总结

1.数组传参可以用 * 数组名
2.求数组的长度可以调用sizeof(数组名)
3.控制输出时有时会输出多有的内容如符号(逗号),可以通过设置tag初始值为0来控制符号输出次数。
在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/码创造者/article/detail/972783
推荐阅读
相关标签
  

闽ICP备14008679号