【Leetcode 1】 两数之和 (Two point双指针 || Map)
发布日期:2021-05-04 19:23:49 浏览次数:22 分类:精选文章

本文共 674 字,大约阅读时间需要 2 分钟。

1. 两数之和

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

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。

示例:

给定 nums = [2, 7, 11, 15], target = 9因为 nums[0] + nums[1] = 2 + 7 = 9所以返回 [0, 1]

代码一(Two point):

class Solution {   public:    vector
twoSum(vector
& nums, int target) { int i=0,j=nums.size()-1; vector
t,ans; t=nums; //nums要排序,顺序会乱,用t记录原来的nums sort(nums.begin(),nums.end()); while(i

在这里插入图片描述

代码二(Map):

class Solution {   public:    vector
twoSum(vector
& nums, int target) { map
m,n; //m记录是否出现过,n记录出现的位置 vector
ans; for(int i=0;i

在这里插入图片描述

上一篇:【一只蒟蒻的刷题历程】 【洛谷】P1119-灾后重建 (最短路Floyed)(容易理解!!!)
下一篇:【一只蒟蒻的刷题历程】 【洛谷】 P1364-医院设置 (BFS || Floyed)

发表评论

最新留言

路过,博主的博客真漂亮。。
[***.116.15.85]2025年03月29日 08时44分24秒