给定一个整数数组 nums 和一个目标值 target,求nums和为target的两个数的下表

2023-04-20,,

这个是来自力扣上的一道c++算法题目:

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum
自己采用的解法还有网上学习来的方法。

暴力方法:(遍历每个元素 xx,并查找是否存在一个值与 target - xtarget−x 相等的目标元素。)

#include<iostream>
using namespace std;
int* twoSum(int nums[],int target)
{
int a[];
for (int i = ; i < (sizeof(nums)/); i++) {
for (int j = i + ; j < (sizeof(nums)/); j++) {
for (int j = i + ; j < (sizeof(nums)/); j++) {
if (nums[j] == target - nums[i]) {
a[]=i;a[]=j;
return a;
}
}
} }
int main()
{
cout<<"请输入对应的数组 :"<<endl;
int wen[],*wen2,q1;
cin>>wen;
cout<<"请输入想要得到的数值 :"<<endl;
cin>>q1;
wen2=twoSum(wen,q1);
cout<<"{"<<wen2[]<<","<<wen2[]<<"}"<<endl;
return ; }

然后就是关于哈希表的应用这种比较简单:

  public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = ; i < nums.length; i++) {
map.put(nums[i], i);
}
for (int i = ; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement) && map.get(complement) != i) {
return new int[] { i, map.get(complement) };
}
}
}

给定一个整数数组 nums 和一个目标值 target,求nums和为target的两个数的下表的相关教程结束。

《给定一个整数数组 nums 和一个目标值 target,求nums和为target的两个数的下表.doc》

下载本文的Word格式文档,以方便收藏与打印。