• Leetcode No.1 Two Sum(c++哈希表实现)


    1. 题目

    1.1 英文题目

    Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
    You may assume that each input would have exactly one solution, and you may not use the same element twice.
    You can return the answer in any order.

    1.2 中文题目

    给定一个整数数组nums,返回数组中“和是某个给定值target”的两个数的下标。假设对于每次输入有且只有一个解。

    1.3输入输出

    输入 输出
    nums = [2,7,11,15], target = 9 [0,1]
    nums = [3,2,4], target = 6 [1,2]
    nums = [3,3], target = 6 [0,1]

    2. 实验平台

    IDE:VS2019
    IDE版本:16.10.1
    语言:c++

    3. 代码

    3.1 功能程序

    #pragma once
    #include<vector>
    #include<map>
    using namespace std;
    
    //主功能
    class Solution {
    public:
        vector<int> twoSum(vector<int>& nums, int target) 
        {
            map<int, int> hashMap; // 声明哈希表,存储已经遍历过的nums,其中nums的元素为key,元素的索引为value
            vector<int> ans; // 存储结果
            for (int i = 0; i < nums.size(); i++) // 遍历nums
            {
                int temp = target - nums[i]; // 定义target与nums[i]的差值
                if (hashMap.count(temp)) // 向前搜索是否有与差值相同的元素,若有
                {
                    ans = { hashMap[temp], i }; // 给出结果
                }
                hashMap[nums[i]] = i; // 将遍历过的nums[i]加入到哈希表hashMap中
            }
            return ans; // 返回结果
        }
    };
    

    3.2 测试程序

    #include "Solution.h"
    #include <vector>
    #include<iostream>
    using namespace std;
    
    // 主程序
    void main()
    {
    	vector<int> nums = { 1,1,2,7,4,2,5 };
    	int target = 4; // 定义输入
    	Solution solution; // 实例化Solution
    	vector<int> result = solution.twoSum(nums, target); // 主算法
    	cout << "[" << result[0] << "," << result[1] << "]" << endl; // 输出结果
    }
    

    4. 代码思路

    构建哈希表,每次循环搜索时,都从搜索当前位置到前面几个元素进行查找

    5. 注意事项

    哈希表会对相同的key值的value进行覆盖处理,这一点需要加以注意。

    作者:云梦士
    本文版权归作者和博客园共有,欢迎转载,但必须给出原文链接,并保留此段声明,否则保留追究法律责任的权利。
  • 相关阅读:
    时间序列表示
    Resnet——深度残差网络(二)
    Resnet——深度残差网络(一)
    基于tensorflow2.0和cifar100的VGG13网络训练
    Android实战项目——家庭记账本(七)
    iOS-基于TCP连接<Scoket-客户端>
    Xcode更新到10.0之后遇到的那些坑:
    cell右侧的状态(accessoryType)
    2020最新cocoapods详细安装和使用
    AFNetworking上传一张或多张图片,并压缩图片节约占用内存
  • 原文地址:https://www.cnblogs.com/yunmeng-shi/p/14923745.html
Copyright © 2020-2023  润新知