nums = [2,7,11,15], target = 9 o

发布时间:2026-05-02 17:02

利用信用卡的返现或者积分兑换,比如Target红卡或Sephora points。 #生活技巧# #节省生活成本# #购物优惠技巧# #价格跟踪#

Leetcode-1.Two Sum

最新推荐文章于 2023-12-29 19:56:56 发布

原创 于 2022-03-15 19:21:34 发布 · 913 阅读

· 0

· 0 ·

CC 4.0 BY-SA版权

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

题目背景

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.

解法一 (暴力法)

class Solution { public: vector<int> twoSum(vector<int>& nums, int target) {vector<int> retnum;for(int i=0;i<nums.size();i++){for(int j=i+1;j<nums.size();j++){if(nums[i]+nums[j]==target){retnum.push_back(i);retnum.push_back(j);return retnum;}}}return retnum; } };

cpp

1234567891011121314151617 解法二:哈希法

#include<iostream> #include<unordered_map> #include<vector> using namespace std; vector<int> twosum(vector<int>& nums,int target){unordered_map<int,int> num2;for(int i=0;i<nums.size();i++){auto it = num2.find(target-nums[i]);if(it!=num2.end()){//unordered_map 中find()返回的是位置,如果没有就是map.end()return {it->second,i};}num2[nums[i]]=i;}return {}; } int main(){vector<int> nums={2,7,11,15} ;for(auto i:twosum(nums,9))cout<<i<<endl;return 0; }

cpp

123456789101112131415161718192021

网址:nums = [2,7,11,15], target = 9 o https://www.yuejiaxmz.com/news/view/1455159

相关内容

TwoSum
测试开发基础之算法(8):二分查找的6种常用应用场景
Leetcode编程实践
四数问题下逻辑运算符的注意事项
matlab程序里nbus=x的意思,没什么用的matlab代码1
一维动态规划精讲
一维动态规划示例
算法
target='
python编程——006实战递归

随便看看