leetcode-Easy-第1期:two sum
原题描述:
Given an array of integers, return indices of the two numbers such that they add up to a specific target
You may assume that each input would have exactly one solution, and you may not use the same element twice.
题目意思
从数组中找出A+B=C,返回A和B在数组中的位置,数组中一定存在A和B相加等于C,并且A和B不能相等
- Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
- 解法
var twoSum = function(array, target) {const len = array.length;// 因为肯定有解,且值不一样,所以数组只有两个值的时候这两个值就为解if (len === 2) return [0, 1]; let obj = {};for(let i = 0; i < len; i++) {let value = target - array[i]; //value in obj判断obj对象是否有一个key为valueif(value in obj ) return [obj[value], i]; //obj对象的key是原来数组的值,value是该值的位置else obj[arrays[i]] = i; }
};其实思路就是:
array = [6,9,10,12],target = 15
obj = {6:0, 9:1, 10:2, 12:3}
15 = 6 + 9 //然后返回6和9对应的值所在位置
leetcode-Easy-第1期:two sum相关推荐
- LeetCode小白菜笔记[1]:Two Sum
LeetCode小白菜笔记[1]:Two Sum 1. Two Sum [Easy] 题目: Given an array of integers, return indices of the two ...
- 【重点】LeetCode 124. Binary Tree Maximum Path Sum
LeetCode 124. Binary Tree Maximum Path Sum 参考链接:http://zxi.mytechroad.com/blog/tree/leetcode-124-bin ...
- 【LeetCode】#39组合总和(Combination Sum)
[LeetCode]#39组合总和(Combination Sum) 加粗样式 给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数 ...
- leetcode easy problem set
*勿以浮沙筑高台* 持续更新........ 题目网址:https://leetcode.com/problemset/all/?difficulty=Easy 1. Two Sum [4m ...
- leetcode 698. Partition to K Equal Sum Subsets | 698. 划分为k个相等的子集(回溯法)
题目 https://leetcode.com/problems/partition-to-k-equal-sum-subsets/ 题解 一上来以为是 dp(想到了左神讲的,将一个数组分成两个尽可能 ...
- LeetCode - Easy - 637. Average of Levels in Binary Tree
Topic Tree Description https://leetcode.com/problems/average-of-levels-in-binary-tree/ Given the roo ...
- LeetCode - Easy - 119. Pascal‘s Triangle II
Topic Array Description https://leetcode.com/problems/pascals-triangle-ii/ Given an integer rowIndex ...
- LeetCode - Easy - 118. Pascal‘s Triangle
Topic Array Description https://leetcode.com/problems/pascals-triangle/ Given a non-negative integer ...
- LeetCode 1973. Count Nodes Equal to Sum of Descendants(DFS)
文章目录 1. 题目 2. 解题 1. 题目 Given the root of a binary tree, return the number of nodes where the value o ...
- Leetcode: mimimum depth of tree, path sum, path sum II
思路: 简单搜索 总结: dfs 框架 1. 需要打印路径. 在 dfs 函数中假如 vector 变量, 不用 & 修饰的话就不需要 undo 2. 不需要打印路径, 可设置全局变量 ans ...
最新文章
- 二层交换机、三层交换机和路由器的基本工作原理区别—Vecloud
- Python基础教程:类的特殊成员及高级特性
- $().each()和$.each()
- 微信“拍一拍”,竟然可以使用Python实现,你get到了吗?
- 网络基本知识(1) ARP解析
- 2、压滤机现场图片和组成部分详细构造
- 1003 C语言输入以某个特殊输入为结束标志
- 怎么查看页面跳转过程_fastcapture注册码怎么获取?FastStone注册码分享
- 台式计算机视频设备打不开,电脑视频设备被占用未能创建视频预览怎么办
- Spacecom:将和信威集团在30天内决定新的收购协议
- 初识webservice 服务
- MAC OS Finder 中快速定位指定路径
- mybatis-spring
- 高斯积分(概率积分)以及它与伽马函数之间的关系
- Python 实现 Discuz论坛附件下载权限绕过漏洞
- 已解决SyntaxError:positional argument follows keyword argument
- li指令 汇编_汇编语言和汇编软件
- 【Map】map集合及特点_IDEA中Debug追踪
- js获取android系统版本号,JS获取系统版本和手机型号
- iPhone开发网站、论坛和博客