javascript初探LeetCode之1.TwoSum

题目

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.

example

Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

分析

这是leetcode上的第一题,难度为easy,就是给定一个数组和一个目标值,求出和为目标值的两个数组元素的index(不可以重复)。

js实现

/* @param {number[]} nums @param {number} target @return {number[]} */ var twoSum = function(nums, target) { var a = []; for(let i = 0;i

注意

这一题思路简单,但是循环最好别用jsforEach函数,因为该函数在遍历完成之前无法跳出,可能造成在已经求出解后的资源浪费。

你可能感兴趣的:(javascript初探LeetCode之1.TwoSum)