两数之和 (简单)

题目描述

给定一个整数数组和一个目标值,找出数组中和为目标值的两个数; 你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。

例如: 给定 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的更多相关文章

  1. 【数据结构】Hash表简介及leetcode两数之和python实现

    文章目录 Hash表简介 基本思想 建立步骤 问题 Hash表实现 Hash函数构造 冲突处理方法 leetcode两数之和python实现 题目描述 基于Hash思想的实现 Hash表简介 基本思想 ...

  2. LeetCode两数之和

    LeetCode 两数之和 题目描述 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标. 你可以假设每种输入只会对应一个答案.但是 ...

  3. leetcode两数之和go语言

    两数之和(Go语言) 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标. 你可以假设每种输入只会对应一个答案.但是,你不能重复 ...

  4. leetcode 两数之和 python

      两数之和     给定一个整数数组和一个目标值,找出数组中和为目标值的两个数. 你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用. 示例: 给定 nums = [2, 7, 11, 1 ...

  5. Leetcode -- 两数之和Ⅰ

    1. 两数之和 题目描述:给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标. 示例:给定 nums = [2, 7, 11, 15 ...

  6. leetcode - 两数之和Ⅳ 输入BST(653)

    题目描述:给定一个二叉搜索树和一个目标结果,如果 BST 中存在两个元素且它们的和等于给定的目标结果,则返回 true. 解题思路:根据二叉搜索树的特点,对二叉搜索树进行中序遍历可以得到一个从小到达排 ...

  7. leetcode 两数之和 II - 输入有序数组

    给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数. 函数应该返回这两个下标值 index1 和 index2,其中 index1 必须小于 index2. 说明: 返回的下标值 ...

  8. Leetcode 两数之和 (散列表)

    给定一个整数数组和一个目标值,找出数组中和为目标值的两个数. 你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用. 示例: 给定 nums = [2, 7, 11, 15], target ...

  9. LeetCode两数之和-Python<一>

    下一篇:LeetCode链表相加-Python<二> 题目:https://leetcode-cn.com/problems/two-sum/description/ 给定一个整数数组和一 ...

随机推荐

  1. Structs2下的MyFirstTest

    1.这是<Struts2-权威指南>第二章的例子 2.博文主要说明在eclipse下如何创建一个struts2项目 3.实现功能:在login.jsp输入用户名和密码,若用户名为scott ...

  2. XADC

    XADC实验 1.XADC概述 Xilinx7系列内部自带一个双通道12位分辨率的高速(1MSPS 1M sample per second)采样速率的模拟混合信号处理模块,双通道的ADC支持单极和差 ...

  3. dajngo ORM查询中select_related的作用,博客主题的定制,从数据库中按照年月筛选时间

    1.dajngo ORM查询中select_related的作用 select_related()方法一次性的把数据库关联的对象都查询出来放入对象中,再次查询时就不需要再连接数据库,节省了后面查询数据 ...

  4. 利用中转输出表制作HijackDll

    [原创]利用中转输出表制作HijackDll(附工具源码)作 者: baixinye时 间: 2012-08-05,16:48:45链 接: http://bbs.pediy.com/showthre ...

  5. spark复习笔记(1)

    使用spark实现work count ---------------------------------------------------- (1)用sc.textFile(" &quo ...

  6. 显示本机 Linux 系统上所有开放的端口列表

    #!bin/bash#作者:liusingbon#功能:从端口列表中观测端口,关闭无用端口对应的服务,降低被意外攻击的可能性ss -nutlp |awk '{print $1,$5}' |awk -F ...

  7. Qt的QSettings类和.ini文件读写

    Detailed Description QSettings类提供了持久的跨平台的应用程序设置.用户通常期望应用程序记住它的设置(窗口大小.位置等)所有会话.这些信息通常存储在Windows系统注册表 ...

  8. Springboot配置文件占位符

    一.配置文件占位符 1.application.properties server.port=8088 debug=false product.id=ID:${random.uuid} product ...

  9. mac下安装 rabbitMq

    1.安装HomeBrew,如果已经安装这一步跳过. 2.用brew install rabbitmq指令即可进行rabbitmq服务的自动安装. 3.安装完成之后会出现一下提示:   rabbit安装 ...

  10. 使用git管理文件版本

    创建版本库 什么是版本库呢?版本库又名仓库,英文名repository,你可以简单理解成一个目录,这个目录里面的所有文件都可以被Git管理起来,每个文件的修改.删除,Git都能跟踪,以便任何时刻都可以 ...