随笔 - 217  文章 - 4  评论 - 4  阅读 - 23587

算法练习——两数之和

这是我练习算法时遇到的一个问题,两数之和

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

Java

复制代码
class Solution {
    public int[] twoSum(int[] nums, int target) {
        HashMap<Integer,Integer> map = new HashMap<>();//使用哈希表
        for(int i=0;i<nums.length;i++){
            int m = target-nums[i];
            if(map.containsKey(m)){
                return new int[]{map.get(m),i};
            }
            map.put(nums[i],i);
        }
        return null;
    }
}
复制代码

c++双重for循环

复制代码
#include<iostream>
#include<vector>
using namespace std;
class Solution
{
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        for (int i = 0; i < nums.size(); i++)
        {
            for (int j = i+1; j < nums.size(); j++)
            {
                if (nums[i] + nums[j] == target) {
                    return{ i,j };
                }
            }
        }
        return {};
    }
};
int main() 
{
    int tar = 7;
    Solution s;
    vector<int> vec;
    vector<int> arr = { 1,2,3,4,5,6,7,8,9,10 };
    vec = s.twoSum(arr, tar);
    for (auto i : vec)
    {
        cout << i << endl;
    }
    return 0;
}
复制代码

 

posted on   跨越&尘世  阅读(46)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署
< 2025年3月 >
23 24 25 26 27 28 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 1 2 3 4 5

点击右上角即可分享
微信分享提示