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

【LeetCode】两数之和

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

你可以假设每种输入只会对应一个答案,并且你不能使用两次相同的元素。

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

示例 1:

输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。

示例 2:

输入:nums = [3,2,4], target = 6
输出:[1,2]

示例 3:

输入:nums = [3,3], target = 6
输出:[0,1]

#include <iostream>
#include <vector>
#include <unordered_map>using namespace std;class Solution 
{
public:vector<int> twoSum(vector<int>& nums, int target){// 1.创建哈希表unordered_map<int, int> numsToIndex;// 存储数组索引vector<int> arrIndex;for (int i = 0; i < nums.size(); i++){int complement = target - nums[i];if (numsToIndex.find(complement) != numsToIndex.end()){arrIndex.push_back(numsToIndex[i]);arrIndex.push_back(i);return arrIndex;}// 2.建立映射numsToIndex[nums[i]] = i;}return arrIndex;}
};int main() {Solution solution;vector<int> nums = { 2, 7, 11, 15 };int target = 9;vector<int> result = solution.twoSum(nums, target);// 输出结果if (!result.empty()) {cout << "Indices of the two numbers that add up to target are: ["<< result[0] << ", " << result[1] << "]" << endl;}else {cout << "No two numbers add up to the target." << endl;}return 0;
}
http://www.lryc.cn/news/424252.html

相关文章:

  • UE5学习笔记11-为拿取武器添加动画
  • 68. 文本左右对齐【 力扣(LeetCode) 】
  • 【中等】 猿人学web第一届 第6题 js混淆-回溯
  • 低、中、高频率段具体在不同应用中的范围是多少
  • Oxford Model600 Model400低温氦压缩机cryogenic helium compressor手侧
  • Golang面试题四(并发编程)
  • 计算机学生高效记录并整理编程学习笔记的方法
  • 【书生大模型实战】L2-LMDeploy 量化部署实践闯关任务
  • 《编程学习笔记之道:构建知识宝库的秘诀》
  • DETR论文,基于transformer的目标检测网络 DETR:End-to-End Object Detection with Transformers
  • untiy有渲染线程和逻辑线程嘛
  • 什么是数据仓库ODS层?为什么需要ODS层?
  • permutation sequence(
  • PCL 三线性插值
  • JVM虚拟机(一)介绍、JVM内存模型、JAVA内存模型,堆区、虚拟机栈、本地方法栈、方法区、常量池
  • Python利用xlrd复制一个Excel中的sheet保留原格式创建一个副本(注:xlrd只能读取xls)
  • 40、Python之面向对象:扩展的对象属性解析顺序(描述符 + MRO)
  • stm32—时钟、定时器和看门狗
  • Windows平台RTSP|RTMP播放器如何实时调节音量
  • Leetcode JAVA刷刷站(10)正则表达式匹配
  • 合并图片为pdf
  • 【Linux Install】Ubuntu20, Windows10 双系统安装
  • Keepalived + LVS实现高可用
  • Gin框架接入Prometheus,grafana辅助pprof检测内存泄露
  • 上海凯泉泵业入职测评北森题库题型分析、备考题库、高分攻略
  • Linux:基础IO
  • 奥运奖牌窥视
  • RUST实现远程操作电脑手机
  • spring01-spring容器启动过程分析
  • RAG与LLM原理及实践(12)--- Milvus RRFRanker的使用场景及源码分析