[Leetcode] [simple] [1] [two numbers and JavaScript]

Title Description

1. The sum of two numbers

Given an integer array nums and a target value target, and ask you to identify the target value of the two integers in the array, and return to their array subscript.

You can assume that each input corresponds to only one answer. However, you can not re-use the same array element.

Example:

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

Because nums [0] + nums [1 ] = 2 + 7 = 9
is returned [0, 1]

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/two-sum
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

 

answer:

Solution 1:

Personal thoughts:

Define two pointers, one pointing to the top, a tail point, the tail to the head continues to advance, the pointer overlap, the head pointer is incremented, tail pointer back to the tail, continue.

Until the two elements referred so far add up to target.

216 ms

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var twoSum = function(nums, target) {
    let start = 0;
    let end = nums.length-1
    while(start <= end){
        if(start === nums.length-1){
            break
        }
        if(start === end){
           start++
            end = nums.length-1
           }
        if(nums[start]+nums[end] === target){
           return[start,end]
        }
        end--
    }
};

 

 

Solution 2:

Already the fastest answer:

Run faster or hash table, define an empty object, through the array, if the target obtained by subtracting the value of the current element has a key object, and outputs [the object corresponding to the key value (index), the current element index];

If the key value is not obtained object, put the object as a key element, as the element corresponding to the index value.

44ms

var twoSum = function (nums, target) {
  let obj = {};
  for (var i = 0; i < nums.length; i++) {
    if (obj[target - nums[i]] !== undefined) {
      return [obj[target - nums[i]], i];
    }
    obj[nums[i]] = i;
  }
};

 

Guess you like

Origin www.cnblogs.com/2463901520-sunda/p/11495081.html