note's People
note's Issues
1. 两数之和
题目
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
解法
暴力遍历
通过两次循环遍历整个数组来寻找,时间为 O(n2)
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function(nums, target) {
let x = 0;
let y = 1;
let find = false;
let ret = [];
let len = nums.length;
for (; x < len - 1; x++) {
if (find === true) break;
for (y = x + 1; y <= len - 1; y++) {
if (nums[x] + nums[y] === target) {
ret = [x, y];
find = true;
break;
}
}
}
return ret;
};
空间换时间
空间换时间,先通过一次循环用一个数组来存储原始数组存在的值,然后在通过一次循环遍历原始数组,寻找对应的下标。
var twoSum = function(nums, target) {
var map = [];
var len = nums.length;
for (let i = 0; i < len; i++) {
map[nums[i]] = i;
}
for (let i = 0; i < len; i++) {
const x = target - nums[i];
if (map[x] !== undefined && map[x] !== i) {
return [i, map[x]]
}
}
return []
}
考察点
- 遍历方法
- 哈希概念
Typescript
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.