您的位置:首页 > 科技 > IT业 > 闯关leetcode——1.Two Sum

闯关leetcode——1.Two Sum

2024/10/6 0:32:50 来源:https://blog.csdn.net/breaksoftware/article/details/141996405  浏览:    关键词:闯关leetcode——1.Two Sum

大纲

  • 题目
    • 地址
    • 内容
  • 解题
    • 代码地址

题目

地址

https://leetcode.com/problems/two-sum/description/

内容

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.

Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].

Example 2:

Input: nums = [3,2,4], target = 6
Output: [1,2]

Example 3:

Input: nums = [3,3], target = 6
Output: [0,1]

Constraints:

  • 2 <= nums.length <= 104
  • -109 <= nums[i] <= 109
  • -109 <= target <= 109
  • Only one valid answer exists.

解题

这题的意思是在一个无序数组中找到两个数字,它们的和是给定的目标数字,并按从小到大的顺序返回它们的下标。
“无序数组”意味着这题逃不掉遍历;“从小到大”意味着遍历方向是从低位开始。
为了表述方便,我们称这样的一对数字互为朋友数字。
那么这题的思路就很简单了:从低位开始遍历,查看该数是否是已经遍历过的数字的朋友数字。如果是,则返回它们的下标;如果不是,则记录该数的朋友数字和自己下标。
朋友数字和下标需要绑定,即可以通过朋友数字找到下标。
具体一点,比如7和2互为朋友数字。遍历到7的是否,发现之前没有哪个数字是它的朋友,则记录它的朋友数字9-7=2和下标0为{2,0}。遍历到2时,发现它是之前某数(7)的朋友数字,则返回它们的下标[0,1]。

#include <vector>
#include <unordered_map>
using namespace std;class Solution {
public:vector<int> twoSum(vector<int>& nums, int target) {unordered_map<int, int> num_map;for (int i = 0; i < nums.size(); ++i) {if (auto it = num_map.find(nums[i]); it != num_map.end()) {return {it->second, i};}num_map[target - nums[i]] = i;}return {-1, -1};}
};

在这里插入图片描述

代码地址

https://github.com/f304646673/leetcode/tree/main/1-Two-Sum

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com