给定一个整数数组 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

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

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

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/376716

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月3日 下午1:08
下一篇 2023年3月3日 下午1:09

相关推荐