JS斩杀LeetCode(1):Two Sum
来源:互联网 发布:宇宙数控系统编程 编辑:程序博客网 时间:2024/06/05 14:07
题目:
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.
示例:
Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].
原题链接:
https://leetcode.com/problems/two-sum/#/description
解法①
/** * @param {number[]} nums * @param {number} target * @return {number[]} */var twoSum = function(nums, target) { var result = []; for (var i = 0; i < nums.length; i++) { for (var j = i+1; j < nums.length; j++) { if (nums[i] + nums[j] === target && i !== j) { result[0] = i; result[1] = j; return result; } } } return result;};这种解法比较常规,时间复杂度为O(n²)。通过两个for循环遍历所有元素,当两元素之和等于target,且下标不等时,返回结果。
解法②
/** * @param {number[]} nums * @param {number} target * @return {number[]} */var twoSum = function(nums, target) { var temp = []; for (var i = 0; i < nums.length; i++) { var cur = nums[i]; if (temp[target - cur] !== undefined) { return [temp[target - cur], i]; } temp[cur] = i; } return [];};这种解法相比第一种更高效,时间复杂度为O(n)。将数组值作为temp数组的下标,符合条件则返回结果。
阅读全文
2 1
- JS斩杀LeetCode(1):Two Sum
- leetcode (1) Two Sum js代码实现
- LeetCode(1)Two Sum
- LeetCode(1)Two Sum
- leetcode(1) - Two Sum
- leetcode(1)Two Sum
- LeetCode Two Sum(C/JS)
- LeetCode (1)Two Sum | LeetCode
- LeetCode 1 - Two Sum
- leetcode 1 Two Sum
- Leetcode【1】:Two Sum
- [leetcode 1] Two Sum
- 【leetcode-1】Two Sum
- [leetcode 1] Two Sum
- [Leetcode] 1 - Two Sum
- LeetCode (1) Two Sum
- LeetCode 1:《Two Sum》
- LeetCode | #1 Two Sum
- java 基于socket套接字的低层次网络编程
- 多条Shell命令的组合连接
- USACO-Section1.1 Greedy Gift Givers[...]
- 219. Contains Duplicate II 答案
- Codeforces 455C. Civilization (树的直径+并查集)
- JS斩杀LeetCode(1):Two Sum
- swift-oc 交互记录
- TCP的定时器系列 — SYNACK定时器
- 内部类的闭包与回调
- 用ffmpeg+qt做点有趣的事(3)----- ffmpeg解码流程
- SVN Unable to connect to a repository at URL
- 用python抓取百万网易云热门评论[转载]
- 搜索-B
- TCP的定时器系列 — 保活定时器(有图有代码有真相!!!)