-
Notifications
You must be signed in to change notification settings - Fork 634
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
字节&leetcode1:两数之和 #4
Comments
let nums = [2, 7, 11, 15],
target = 26;
function getSumIndex(arr1, sum) {
let i = 0;
while (i < arr1.length) {
const j = arr1.slice(i + 1).findIndex(item => arr1[i] + item === sum);
if (j !== -1) {
console.log([i, i + 1 + j]);
return [i, i + 1 + j];
} else {
i++;
}
}
console.log("[]");
return [];
}
getSumIndex(nums, target); |
解题思路:
时间复杂度:O(n) 代码实现: const twoSum = function(nums, target) {
let map = new Map()
for(let i = 0; i< nums.length; i++) {
let k = target-nums[i]
if(map.has(k)) {
return [map.get(k), i]
}
map.set(nums[i], i)
}
return [];
}; |
function findSumIdx(arr, target){
let num1 = null, num2 = null;
for(let i=0; i<arr.length; i++){
for(let j=i; j<arr.length-i; j++){
if(arr[i] + arr[j] ===target){
num1 = i,num2 = j;
break;
}
}
if(num1 && num2) break;
}
return [num1, num2];
} |
|
用一个hash来检查是否已经存在过该元素,用一次循环。要返回的是数组下标的索引 /**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function(nums, target) {
var map = {}
for(var i = 0; i < nums.length;i++){
if(map.hasOwnProperty(target-nums[i])){ // 边循环边检查,有就直接返回
return [map[target-nums[i]], i]
}else{ // 没有就添加到哈希表里头
map[nums[i]] = i // key为值,下标为索引
}
}
}; |
function getTargetFromArray(nums, target){ |
let getSumIndex = ()=>{ |
|
var twoSum = function(nums, target) {
let len = nums.length
for(let i=0;i<len;i++){
if(nums.lastIndexOf(target-nums[i])!==-1&&nums.lastIndexOf(target-nums[i])!==i){
return [i,nums.lastIndexOf(target-nums[i])]
}
}
}; var twoSum = function(nums, target) {
let len = nums.length
let obj = {}
let cha
for(let i=0;i<len;i++){
cha = target - nums[i]
if(obj[cha]!==undefined){
return [obj[cha],i]
}
obj[nums[i]] = i
}
}; |
思路:
|
|
function(nums, target){ } |
请问用map实现和用纯对象实现,对比来说map实现会有什么优势吗 |
the time complexity of map calling method is O(1), so using map makes the total time complexity very small. |
// 正整数数组,可以使用 {} 来存储数据
var twoSum = function(nums, target) {
let map = {}
for(let i = 0; i< nums.length; i++) {
let k = target-nums[i]
if(map[k]) {
return [map[k, i]
}
map[nums[i]] = i
}
return [];
}; |
var twoSum = function(nums, target) {
let tmpMap = new Map();
for(let index = 0;index < nums.length; index ++) {
let toSearch = target - nums[index];
if(tmpMap.has(toSearch)) {
return [tmpMap.get(toSearch), index]
}
tmpMap.set(nums[index], index);
}
}; |
|
题目地址(1. 两数之和)https://leetcode-cn.com/problems/two-sum 题目描述
前置知识
公司
思路最容易想到的就是暴力枚举,我们可以利用两层 for 循环来遍历每个元素,并查找满足条件的目标元素。不过这样时间复杂度为 O(N^2),空间复杂度为 O(1),时间复杂度较高,我们要想办法进行优化。 这里我们可以增加一个 Map 记录已经遍历过的数字及其对应的索引值。这样当遍历一个新数字的时候就去 Map 里查询 target 与该数的差值是否已经在前面的数字中出现过。如果出现过,就找到了答案,就不必再往下继续执行了。 关键点
代码
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
const twoSum = function (nums, target) {
const map = new Map();
for (let i = 0; i < nums.length; i++) {
const diff = target - nums[i];
if (map.has(diff)) {
return [map.get(diff), i];
}
map.set(nums[i], i);
}
}; Go Code: func twoSum(nums []int, target int) []int {
m := make(map[int]int)
for i, _ := range nums {
diff := target - nums[i]
if j, ok := m[diff]; ok {
return []int{i, j}
} else {
m[nums[i]] = i
}
}
return []int{}
} CPP Code: class Solution {
public:
vector<int> twoSum(vector<int>& A, int target) {
unordered_map<int, int> m;
for (int i = 0; i < A.size(); ++i) {
int t = target - A[i];
if (m.count(t)) return { m[t], i };
m[A[i]] = i;
}
return {};
}
}; 复杂度分析
更多题解可以访问我的 LeetCode 题解仓库:https://github.com/azl397985856/leetcode 。 目前已经 40K star 啦。 关注公众号力扣加加,努力用清晰直白的语言还原解题思路,并且有大量图解,手把手教你识别套路,高效刷题。 |
@sisterAn 请教下 hash 为什么用 Map,而不用 Object 呢? |
|
|
function sum(arr, target) { |
给定一个整数数组
nums
和一个目标值target
,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
附leetcode地址:leetcode
可结合 腾讯&leetcode15:三数之和 一起查看
The text was updated successfully, but these errors were encountered: