【LeetCode】 两数之和 twoSum
两数之和 (简单)
题目描述
给定一个整数数组和一个目标值,找出数组中和为目标值的两个数; 你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。
例如: 给定 nums = [2,7,11,15] ,target = 9 因为 nums[0] + nums[1] = 9; 因此返回 [0,1];
v1.0代码如下: 正数、0或重复值通过测试; 异常用例: [-1, -2, -3, -4, -5] -8; 输出 []
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function(nums, target) {
var tmp = target;
var result = [];
for(i=0; i < nums.length; i++){
if(nums[i] <= tmp){
tmp = target - nums[i];
var last = nums.length - i - 1;
for(j=0; j < nums.length; j++){
if(nums[j] === tmp && j != i){
result.push(i,j);
return result;
}
}
}
}
return result;
};
分析: 首先想到使用减法得到另一个数,因此考虑过滤掉所有小于target的值;但未考虑负数的情况。 解决方案,去掉外循环的if判断
官方解析:
上述方案属于暴力解法,遍历每个元素并查找是否有一个值与target-x相等的元素。 时间复杂度 O(n²);空间复杂度 O(1);
方法2 两遍哈希表
为了优化时间复杂度,需要更有效的方法来检查数组中是否存在目标元素。如果存在,需要知道其索引。保持数组中每个元素与其索引相互对应的最好方法是哈希表。
通过以空间换取速度的方式,我们可以将查找时间从 O(n)降低到 O(1)。哈希表正是为此目的而构建的,它支持以 近似 恒定的时间进行快速查找。我用“近似”来描述,是因为一旦出现冲突,查找用时可能会退化到 O(n)。但只要你仔细地挑选哈希函数,在哈希表中进行查找的用时应当被摊销为 O(1)。
算法思路: 使用两次迭代。在第一次迭代中,将每个元素的值和其索引添加到表中,在第二次迭代中,检查每个元素所对应的目标元素(target - nums[i])是否存在于表中。同时注意该元素不能是该元素本身。
Code:
/**
* 在js中没有hashTable,但是js的Object属性是基于
* hashTable实现的,因此可以有:
* var person = {};
* person['name'] = "Test"
* 因此,利用该特性,封装hashTable的函数即可使用
**/
var twoSum = function(nums, target){
var result = [];
for(i=0; i < nums.length; i++>){
map.add(nums[i], i);
}
for(i=0; i < nums.length; i++){
var tmp = target - nums[i];
if(map.containsKey(tmp) && map.getValue(tmp) != i){
result.push(i);
result.push(map.getValue(tmp));
}
}
}
var map = new HashTable();
var HashTable = function(){
// HashTable 一般操作包括:
// add(k, v); getValue(k); remove(k);
// containsValue(v); containsKey(k);
// getValues(); getSize(); getKeys();
// Clear();
var size = 0;
var entry = new Object();
this.add = function(k, v){
if(!this.containsKey(k)){
size++;
entry[k] = v;
}
}
this.getValue = function(k){
return this.containsKey(k) ? entry[k] : null;
}
this.remove = function(k){
if(this.containsKey(k) && delete entry[k]{
size--;
}
}
this.containsKey = function(k){
return (k in entry);
}
this.containsValue = function(v){
for (var prop in entry){
if(entry[prop] == value){
return true;
}
}
return false;
}
this.getValues = function(){
var values = new Array();
for(var prop in entry){
values.push(entry[prop]);
}
return values;
}
this.getKeys = function(){
var keys = new Array();
for(var prop in entry){
keys.push(prop);
}
return keys;
}
this.getSize = function(){
return size;
}
this.clear = function(){
size = 0;
entry = new Object();
}
}
在上述方法中,时间复杂度为O(n);哈希表的引入使得查找元素的时间缩短到O(1); 空间复杂度为 O(n);
代码为js编写,因此在方案2中需要自行实现一个Hash Table
thead > tr > th {
text-align: left;
border-bottom: 1px solid;
}
table > thead > tr > th,
table > thead > tr > td,
table > tbody > tr > th,
table > tbody > tr > td {
padding: 5px 10px;
}
table > tbody > tr + tr > td {
border-top: 1px solid;
}
blockquote {
margin: 0 7px 0 5px;
padding: 0 16px 0 10px;
border-left: 5px solid;
}
code {
font-family: Menlo, Monaco, Consolas, "Droid Sans Mono", "Courier New", monospace, "Droid Sans Fallback";
font-size: 14px;
line-height: 19px;
}
body.wordWrap pre {
white-space: pre-wrap;
}
.mac code {
font-size: 12px;
line-height: 18px;
}
pre:not(.hljs),
pre.hljs code > div {
padding: 16px;
border-radius: 3px;
overflow: auto;
}
/** Theming */
.vscode-light,
.vscode-light pre code {
color: rgb(30, 30, 30);
}
.vscode-dark,
.vscode-dark pre code {
color: #DDD;
}
.vscode-high-contrast,
.vscode-high-contrast pre code {
color: white;
}
.vscode-light code {
color: #A31515;
}
.vscode-dark code {
color: #D7BA7D;
}
.vscode-light pre:not(.hljs),
.vscode-light code > div {
background-color: rgba(220, 220, 220, 0.4);
}
.vscode-dark pre:not(.hljs),
.vscode-dark code > div {
background-color: rgba(10, 10, 10, 0.4);
}
.vscode-high-contrast pre:not(.hljs),
.vscode-high-contrast code > div {
background-color: rgb(0, 0, 0);
}
.vscode-high-contrast h1 {
border-color: rgb(0, 0, 0);
}
.vscode-light table > thead > tr > th {
border-color: rgba(0, 0, 0, 0.69);
}
.vscode-dark table > thead > tr > th {
border-color: rgba(255, 255, 255, 0.69);
}
.vscode-light h1,
.vscode-light hr,
.vscode-light table > tbody > tr + tr > td {
border-color: rgba(0, 0, 0, 0.18);
}
.vscode-dark h1,
.vscode-dark hr,
.vscode-dark table > tbody > tr + tr > td {
border-color: rgba(255, 255, 255, 0.18);
}
.vscode-light blockquote,
.vscode-dark blockquote {
background: rgba(127, 127, 127, 0.1);
border-color: rgba(0, 122, 204, 0.5);
}
.vscode-high-contrast blockquote {
background: transparent;
border-color: #fff;
}
-->
code {
color: #C9AE75; /* Change the old color so it seems less like an error */
font-size: inherit;
}
/* Page Break : use
to insert page break-------------------------------------------------------- */
.page {
page-break-after: always;
}
-->
【LeetCode】 两数之和 twoSum的更多相关文章
- 【数据结构】Hash表简介及leetcode两数之和python实现
文章目录 Hash表简介 基本思想 建立步骤 问题 Hash表实现 Hash函数构造 冲突处理方法 leetcode两数之和python实现 题目描述 基于Hash思想的实现 Hash表简介 基本思想 ...
- LeetCode两数之和
LeetCode 两数之和 题目描述 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标. 你可以假设每种输入只会对应一个答案.但是 ...
- leetcode两数之和go语言
两数之和(Go语言) 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标. 你可以假设每种输入只会对应一个答案.但是,你不能重复 ...
- leetcode 两数之和 python
两数之和 给定一个整数数组和一个目标值,找出数组中和为目标值的两个数. 你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用. 示例: 给定 nums = [2, 7, 11, 1 ...
- Leetcode -- 两数之和Ⅰ
1. 两数之和 题目描述:给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标. 示例:给定 nums = [2, 7, 11, 15 ...
- leetcode - 两数之和Ⅳ 输入BST(653)
题目描述:给定一个二叉搜索树和一个目标结果,如果 BST 中存在两个元素且它们的和等于给定的目标结果,则返回 true. 解题思路:根据二叉搜索树的特点,对二叉搜索树进行中序遍历可以得到一个从小到达排 ...
- leetcode 两数之和 II - 输入有序数组
给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数. 函数应该返回这两个下标值 index1 和 index2,其中 index1 必须小于 index2. 说明: 返回的下标值 ...
- Leetcode 两数之和 (散列表)
给定一个整数数组和一个目标值,找出数组中和为目标值的两个数. 你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用. 示例: 给定 nums = [2, 7, 11, 15], target ...
- LeetCode两数之和-Python<一>
下一篇:LeetCode链表相加-Python<二> 题目:https://leetcode-cn.com/problems/two-sum/description/ 给定一个整数数组和一 ...
随机推荐
- C# 各种加密
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Sec ...
- UITextField 文本框 只能输入数字 且保留2位小数 实现
http://blog.sina.com.cn/s/blog_aa7579f601015xvx.html #pragma mark - #pragma mark UITextField - (BOOL ...
- JS全选的操作
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- vue项目引入外部字体
1.UI设计图有"华文黑体",担心客户端没有该字体,将"huawen.ttf"字体文件,放入项目中: 2.创建一个font.scss(或font.css)文件: ...
- 使用`html-webpack-plugin`插件配置启动页面
由于使用`--contentBase`指令的过程比较繁琐,需要指定启动的目录,同时还需要修改index.html中script标签的src属性,所以推荐大家使用`html-webpack-plugin ...
- python email模块
python email模块 官方文档 email模块 电子邮件包是一个用于管理电子邮件消息的库.它的特殊设计不用于向SMTP (RFC 2821).NNTP或其他服务器发送任何电子邮件消息;这些是模 ...
- 1121. Damn Single (25)
"Damn Single (单身狗)" is the Chinese nickname for someone who is being single. You are suppo ...
- GUI学习之二十九—QFileDialog学习总结
今天学习的是文件对话框——QFileDialog 一.描述 QFileDialog提供了一个对话框,允许用户选择文件或者目录,也允许用户遍历文件系统,用以选择一个或多个文件或者目录. QFileDia ...
- 与Swing的初见
---------------------------参考菜鸟教程的swing课程学习-------------------- Swing 是一个为Java设计的GUI工具包. Swing是JAVA基 ...
- 【NOIP2016提高A组8.11】种树
题目 分析 题目要求把图删点,删成树. 考虑一下树的定义,点数n=边数m+1 并且,树中点两两之间联通,那么选的点就不能是割点. 可以用tarjan将图中最大的联通块,保证其中点两两之间有不止一条路径 ...