【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/ 给定一个整数数组和一 ...
随机推荐
- 08-Django加载静态文件
1.css文件以及js文件要放在static目录下,static和templates属于同级目录 2.在Django项目的同名项目文件的setting.py中,最后添加静态文件夹static目录路径 ...
- scala学习笔记(8)文件和正则表达式
1.读取行 ---------------------------------------- 要读取文件中所有的行,可以调用scala.io.Source对象的getLine方法: import sc ...
- css控制文本内容显示省略号
1,单行文字显示省略号 div{ width:200px; overflow:hideen; white-space:nowrap; text-overflow:ellipsis; } 2,多行文字显 ...
- lsattr - 显示文件在Linux第二扩展文件系统上的特有属性
SYNOPSIS(总览) lsattr [ -RVadv ] [ files... ] DESCRIPTION(描述) lsattr 显示文件在Linux第二扩展文件系统上的特有属性 OPTIONS( ...
- VB.NET Event RaiseEvent用处
一.代码 Private Sub Form1_Load(ByVal sender As Object, _ ByVal e As System.EventA ...
- 洛谷 P1896 [SCOI2005]互不侵犯 (状态压缩DP)
题目描述 在N×N的棋盘里面放K个国王,使他们互不攻击,共有多少种摆放方案.国王能攻击到它上下左右,以及左上左下右上右下八个方向上附近的各一个格子,共8个格子. 注:数据有加强(2018/4/25) ...
- Codeforces 907 矩阵编号不相邻构造 团操作状压DFS
A. #include <bits/stdc++.h> #define PI acos(-1.0) #define mem(a,b) memset((a),b,sizeof(a)) #de ...
- 1130. Infix Expression (25)
Given a syntax tree (binary), you are supposed to output the corresponding infix expression, with pa ...
- u-boot 用哪个lds链接脚本
顶层Makefile文件中 : ifndef LDSCRIPT #LDSCRIPT := $(srctree)/board/$(BOARDDIR)/u-boot.lds.debug ifd ...
- unkown类型
1,任何类型的值都可以赋给 unkown类型 2. 如果没有类型断言或基于控制流的类型细化时 unknown 不可以赋值给其它类型,此时它只能赋值给 unknown 和 any 类型 3. 如果没有类 ...