当前位置: 首页 > news >正文

闯关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};}
};

在这里插入图片描述

http://www.lryc.cn/news/432188.html

相关文章:

  • 02 Shell Script注释和debug
  • 如何设计项目架构
  • OTG配置为USB盘之二
  • 如何使用 PHP 函数与其他 Web 服务交互?
  • .NetCore+vue3上传图片 Multipart body length limit 16384 exceeded.
  • 机器学习如何用于音频分析?
  • 适合程序员在周末阅读的历史书籍:理解人性和世界
  • 探索Mem0:下一代人工智能与机器学习内存管理基础设施(二)Mem0+Ollama 部署运行
  • C++入门10——stack与queue的使用
  • 詳細解析軟路由與代理爬蟲池-okeyproxy
  • 视频监控管理平台LntonAIServer视频智能分析噪声检测应用场景
  • 技术分享-商城篇-用户中心-注销修改(二十三)
  • Linux-实用指令
  • 【MySQL00】【 杂七杂八】
  • 计算机网络 第2章 物理层
  • 解决:Module build failed (from ./node_modules/sass-loader/dist/cjs.js)问题
  • 【 html+css 绚丽Loading 】 000041 三才移形三角
  • ASP.NET Core 入门教学十六 防止常见的Web攻击
  • 单刀直入@ComponentScan之 资源加载
  • SAPUI5基础知识25 - 聚合绑定(Aggregation Binding)
  • 【Python 千题 —— 算法篇】寻找两个正序数组的中位数
  • Autoware 定位之初始姿态输入(九)
  • C# 自定义传值窗体-适合多参数传值
  • Ubuntu20.04+ros-noetic配置Cartographer
  • Visual Studio 2022 下载和安装
  • 在 Windows 环境下实现免密登录 Linux 服务器
  • Computer Exercise
  • 利用Stable Diffusion AI图像模型评估智能车模型算法表现(下篇)
  • 音视频入门基础:WAV专题(8)——FFmpeg源码中计算WAV音频文件AVStream的time_base的实现
  • springboot中的请求过滤filter与拦截interceptor分析