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

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

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

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

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

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

#include<iostream>
using namespace std;
int* twoSum(int nums[],int target)
{
    int a[2];
     for (int i = 0; i < (sizeof(nums)/4); i++) {
           for (int j = i + 1; j < (sizeof(nums)/4); j++) {
           for (int j = i + 1; j < (sizeof(nums)/4); j++) {
                if (nums[j] == target - nums[i]) {
                        a[0]=i;a[1]=j;
                    return a;
                }
            }
    }

}
int main()
{
    cout<<"请输入对应的数组 :"<<endl;
    int wen[],*wen2,q1;
    cin>>wen;
    cout<<"请输入想要得到的数值 :"<<endl;
    cin>>q1;
    wen2=twoSum(wen,q1);
    cout<<"{"<<wen2[0]<<","<<wen2[1]<<"}"<<endl;
    return 0;

}

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

  public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            map.put(nums[i], i);
        }
        for (int i = 0; i < nums.length; i++) {
            int complement = target - nums[i];
            if (map.containsKey(complement) && map.get(complement) != i) {
                return new int[] { i, map.get(complement) };
            }
        }
}
原文地址:https://www.cnblogs.com/dazhi151/p/12577396.html