search

Home  >  Q&A  >  body text

javascript - Please explain the following algorithm code

is the code about this algorithm, implemented in javascript, but I don’t understand the algorithm below. Ask God to explain.

var twoSum = function(nums, target) {
    var ret = [];
    var exist = {};
    for(var i = 0; i < nums.length; i++){
        if(typeof(exist[target - nums[i]]) !== 'undefined'){
            ret.push(exist[target - nums[i]]);
            ret.push(i + 1);
        }
        
        exist[nums[i]] = i + 1;
    }
    
    return ret
};
習慣沉默習慣沉默2727 days ago946

reply all(1)I'll reply

  • 淡淡烟草味

    淡淡烟草味2017-07-05 10:43:45

    The questioner can try to use examples to read through the code. Here is my opinion:

    For example, just click on the example in the screenshot:

    The for loop mainly traverses the first parameter array, and then it does two key steps:

    Let’s look at the one after if first, exist[nums[i]] = i + 1; This sentence will be executed in every loop. exist here means a dictionary. For example, the first number traversed is 2 (i =0), so exist saves the key-value pair: {2:1}, so after one loop, exist will be:
    Array conversely, "element value": the key value of "array index + 1" to the dictionary.

    Next, let’s look at the judgment in if. Of course, when i=0 in the for loop, exist has not yet injected the key-value pair, and the if expression is false

    But when i=1, exist[target-nums[1]] means exist[9-7] = exist[2]. Isn’t this the first key-value pair of exist that was injected when i=0? What? So, save the value of the corresponding key-value pair (actually the index of the original value + 1 in the original array) to ret, and then save the current i+1 to ret... Finally, after the loop is completed, return to ret , so we got [1,2] ps: The answer to the example given by the questioner is inconsistent with the code.

    Summary: The core of this algorithm is to use the object exist to store the array elements that have been traversed, and use target-nums[i] to indirectly use exist to find whether there are elements that meet the conditions among the elements that have been traversed in the array.

    reply
    0
  • Cancelreply