leetcode – 1. two sum

Degree

Easy ★ (*´╰╯`๓)♬

Description:

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:

1
2
3
4
Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

Ideas

  • 获取数组中的第一个元素
  • 找到除这个元素之外的其他元素,让它们相加,跟target进行对比
  • 如果和target相等,就返回两个元素所在的index
  • 重复1-3的步骤

Code

1
2
3
4
5
6
7
8
9
10
11
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){
result.push(i,j);
}
}
}
return result;
};