栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

Leetcode-1.Two Sum

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Leetcode-1.Two Sum

题目背景

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 twoSum(vector& nums, int target) {
	vector retnum;
	for(int i=0;i 
解法二:哈希法 
#include
#include
#include
using namespace std;
vector twosum(vector& nums,int target){
	unordered_map num2;
	for(int i=0;isecond,i};
		}
		num2[nums[i]]=i;
	}
	return {};
} 
int main(){
	vector nums={2,7,11,15} ;
	for(auto i:twosum(nums,9))
		cout<
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/768775.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号