1.两数之和(Two Sum) C++
暴力法可解决,速度很慢。
解决办法:哈希表
知识点:
- map的构造
- 遍历map使用迭代器,判断条件
- 插入 pair<int,int>
- 寻找key是否存在
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
map<int,int> m;
map<int,int>::iterator itr;
vector<int> ans;
for(int i=; i<nums.size(); i++)
{ if(i == )
{
m.insert(pair<int,int>(nums.at(i),i));
continue;
} itr = m.find(target-nums.at(i));
if(itr != m.end())
{
ans.push_back(itr->second);
ans.push_back(i);
return ans;
}
m.insert(pair<int,int>(nums.at(i),i));
}
}
};
1.两数之和(Two Sum) C++的更多相关文章
- 领扣-1/167 两数之和 Two Sum MD
Markdown版本笔记 我的GitHub首页 我的博客 我的微信 我的邮箱 MyAndroidBlogs baiqiantao baiqiantao bqt20094 baiqiantao@sina ...
- [Swift]LeetCode1 .两数之和 | Two Sum
Given an array of integers, return indices of the two numbers such that they add up to a specific ta ...
- 两数之和 Two Sum
给定一个整数数列,找出其中和为特定值的那两个数. 你可以假设每个输入都只会有一种答案,同样的元素不能被重用. 示例: 给定 nums = [2, 7, 11, 15], target = 9 因为 n ...
- c++谭浩强教材教学练习例题1.2 求两数之和 为什么sum=a+b;sum的值为65538
第一章 #include <iostream>using namespace std; int main(){ int a,b,sum; sum=a+b; cin>>a> ...
- LeetCode 1:两数之和 Two Sum
题目: 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标. 你可以假设每种输入只会对应一个答案.但是,你不能重复利用这个数组中 ...
- LeetCode 653. 两数之和 IV - 输入 BST(Two Sum IV - Input is a BST)
653. 两数之和 IV - 输入 BST 653. Two Sum IV - Input is a BST 题目描述 给定一个二叉搜索树和一个目标结果,如果 BST 中存在两个元素且它们的和等于给定 ...
- LeetCode_#1_两数之和 Two Sum_C++题解
1. 两数之和 Two Sum 题目描述 Given an array of integers, return indices of the two numbers such that they ad ...
- LeetCode 170. Two Sum III - Data structure design (两数之和之三 - 数据结构设计)$
Design and implement a TwoSum class. It should support the following operations: add and find. add - ...
- LeetCode 371. Sum of Two Integers (两数之和)
Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -. Exam ...
随机推荐
- postgreSql——时区问题
timestamptz.timestamp SELECT ts AT TIME ZONE 'UTC' FROM ( VALUES (timestamptz '2012-03-05 17:00:00+0 ...
- Bootstrap 3 媒体查询
可以参考 Bootstrap 的媒体查询,写网站. html: <div class="bootstrap-3-media"> <p>Mobile-Fir ...
- progressBar显示百分比
this.lab_AllFiles.Text = progressBarAllFile.Value * 100 / progressBarAllFile.Maximum + "%" ...
- activity 运行流程图
- go 接口以及对象传递
// Sample program to show how to use an interface in Go. package main import ( "fmt" ) // ...
- git 修改默认编辑器
vim,notepad(windows自带),notepad++ 当然要选notepad++ 1.首先下载notepad++ 2.将notepad++安装目录放到path中 3.git config ...
- ASP.net MVC模式介绍(一)
一.ASP.NET 支持三种不同的开发模式:Web Pages(Web 页面).MVC(Model View Controller 模型-视图-控制器)表现层.Web Forms(Web 窗体) mv ...
- eclipse中启动 Eclipse 弹出“Failed to load the JNI shared library jvm.dll”错误
原因1:给定目录下jvm.dll不存在. 对策:(1)重新安装jre或者jdk并配置好环境变量.(2)copy一个jvm.dll放在该目录下. 原因2:eclipse的版本与jre或者jdk版本不一致 ...
- MySQL字段拼接Concat
有时候,从数据库中拿出的数据并不是我们想要的格式,比如,有以下的vendors表 如果,想以 name (location)的格式展现出来,那么就要用到MySQL的Concat了. Concat()拼 ...
- 力扣(LeetCode)389. 找不同
给定两个字符串 s 和 t,它们只包含小写字母. 字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母. 请找出在 t 中被添加的字母. 示例: 输入: s = "abcd&quo ...