【Two Sum】cpp

题目

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

 

代码

复制代码
class Solution {
public:
    vector<int> twoSum(vector<int> &numbers, int target) {
        std::vector<int> ret_vector;
        std::map<int,int> value_index;
        for (int i = 0; i < numbers.size(); ++i)
        {
            const int gap = target - numbers[i];
            if (value_index.find(gap) != value_index.end())
            {
                ret_vector.push_back(std::min(i+1,value_index[gap]+1));
                ret_vector.push_back(std::max(i+1,value_index[gap]+1));
                break;
            }
            else
            {
                value_index[numbers[i]] = i; 
            }
        }
        return ret_vector;
    }
};
复制代码

 

Tips:

元素无序且要求复杂度O(n)的,就可以用hashmap解决。

网上有的算法先遍历一遍numbers获得所有元素的map<value,index>,再进行后续的计算。这样的算法没有考虑数组元素重复的case

比如:

numbers = [0,2,4,0]

target = 0

===========================================

第二次过此题,大体思路非常明确。额外开一个hashmap,访问数组一次就搞定。

复制代码
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
            vector<int> ret;
            unordered_map<int, int> value_index;
            for ( int i=0; i<nums.size(); ++i )
            {
                if ( value_index.find(target-nums[i])!=value_index.end() )
                {
                    ret.push_back(i+1);
                    ret.push_back(value_index[target-nums[i]]+1);
                    break;
                }
                value_index[nums[i]] = i;
            }
            std::sort(ret.begin(), ret.end());
            return ret;
    }
};
复制代码

tips:

有三个细节需要注意:

1. [3, 2, 4] 6 对于这种类型的,一定要把value_index[nums[i]]=i放在if语句的后面,要不然同一个元素3就被用了两次

2. 题目要返回的index并不是数组下标,而是数组下标加1,且返回的值要求有序

posted on   承续缘  阅读(318)  评论(0编辑  收藏  举报

编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?

导航

< 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

统计

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