• Welcome to the world's largest Chinese hacker forum

    Welcome to the world's largest Chinese hacker forum, our forum registration is open! You can now register for technical communication with us, this is a free and open to the world of the BBS, we founded the purpose for the study of network security, please don't release business of black/grey, or on the BBS posts, to seek help hacker if violations, we will permanently frozen your IP and account, thank you for your cooperation. Hacker attack and defense cracking or network Security

    business please click here: Creation Security  From CNHACKTEAM

Recommended Posts

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

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

您可以按任意顺序返回答案。

示例1:

输入:nums=[2,7,11,15],目标=9

输出:[0,1]

说明:因为nums[0] nums[1]==9,所以返回[0,1]。

示例2:

输入:nums=[3,2,4],目标=6

输出:[1,2]

示例3:

输入:nums=[3,3],目标=6

输出:[0,1]

提示:

2=nums.length=104

-109=nums=109

-109=目标=109

只有一个有效的答案。

想法:

哈希算法,用STL的map就行了。

代码:

类别解决方案{

公共:

矢量二和(矢量数,整数目标){

mapint,int another _ val _ to _ idx

for(int I=0;I nums . size();i ){

int another _ val=target-nums

auto it=another _ val _ to _ idx . find(another _ val);

如果(它!=another_val_to_idx.end()) {

返回{i,it-second };

}

other _ val _ to _ idx[nums]=I;

}

return { };

}

};

资料来源:LeetCode

链接:https://leetcode.cn/problems/two-sum

版权归领网所有。商业转载请联系官方授权,非商业转载请注明出处。

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now