Two Sum

Description:

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.

Thinking:

const twoSum = (nums, target) => {
  // create an  Object Dictionary
  const exsitedHash = {}

  //loop through the array 'nums',we need to store the index of nums as the value and the num as the key in the Object Dictionary
  
  for (const [index, num] of nums.entries()) {
    //check if the curremt item in the Object Dictionary has a value(the index in the nums)
    
    // if the value(the index in the nums) exists, it means current item has a previous counterpart, their sum is equalto the target,
    // we can return the value(the index in the nums) of current item in the Object Dictionary and the index of previous counterpart item in the nums array
   
    // if the vlaue(the index in the nums) is not exist, store the value(the index in the nums)
    
    if (exsitedHash[num] !== undefined) {
      return [exsitedHash[num], index]
    }else{
      existedHash[num]=index
    }
  }
}