# LeetCode.1 两数之和(Two Sum)(JS)

cvSoldier

## 二、优秀答案

``````/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function(nums, target) {
const comp = {};
for(let i=0; i<nums.length; i++){
if(comp[target - nums[i] ]>=0){
return [ comp[target - nums[i] ] , i]
}
comp[nums[i]] = i
}
};``````

``comp[target-nums[i]] = i``

``````if(comp[target - nums[i] ]>=0){
return [ comp[target - nums[i] ] , i]
}``````

## 三、我的答案

``````/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function (nums, target) {
function isEqualToTarget(num1, num2) {
if (num1 + num2 === target) {
return true
} else {
return false
}
}

function findTargetItem(arr, oldArr) {
for (let i = 0; i < arr.length - 1; i++) {
for (let j = i + 1; j < arr.length; j++) {
if (isEqualToTarget(arr[i], arr[j])) {
return [oldArr.indexOf(arr[i]), oldArr.length - 1 - oldArr.reverse().indexOf(arr[j])]
}
}
}
}
const oldArray = nums.slice(0)
nums.sort((a, b) => a - b)
let tailIndex = nums.findIndex((value, index) => {
return value >= target - nums[0] && index !== 0
})
if (tailIndex === -1) { // [5, 7, 11, 12] 18
return findTargetItem(nums, oldArray)
} else if (isEqualToTarget(nums[0], nums[tailIndex])) {
return [oldArray.indexOf(nums[0]), oldArray.length - 1 - oldArray.reverse().indexOf(nums[tailIndex])]
} else {
nums.length = tailIndex + 1
return findTargetItem(nums, oldArray)
}
};``````

``````nums.sort((a, b) => a - b)
let tailIndex = nums.findIndex((value, index) => {
return value >= target - nums[0] && index !== 0
})``````

113 声望
12 粉丝
0 条评论