简体   繁体   中英

LeetCode EASY TwoSum Explanation

Leetcode Question

I have analyzed the answer for the Leetcode question and am asking for whether my reasoning is correct. I tried analyzing when num = 2 and when num = 7 . The analyses are separated by //.

function twoSum(nums, target) {
  var result = []
  nums.forEach(function(num, i) {
    var diff = target - num
    var k = nums.indexOf(diff)
    if (k > -1 && k !== i) {
       result[0] = i
       result[1] = k
    }
  })
  return result
}
twoSum([2,7,11,15], 9)
var diff = target - num

For 2, diff = 9 - 2 = 7. // For 7, diff = 9 - 7 = 2

var k = nums.indexOf(diff)

indexOf(7) = 1 → k = 1. // indexOf(2) = 0 → k = 0.

if (k > -1 && k !== i)

1 > -1 && 1 !== 0. // 0 > -1 && 0 !== 1.

result[0] = i

result[0] = 0. // result[0] = 1

result[1] = k

result[1] = 1. // result[1] = 0

return result

[0,1] // [1, 0]

So the answer is supposed to be [0,1] but when num = 7 I get [1,0] and was wondering why the function is accepted as the correct answer when I get both [0,1] and [1,0].

Because your answer doesn't need to be sorted. both [0,1] and [1,0] are correct.

You can return the answer with any order.

see the leetcode description

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM