• Author: Chen Da Yu Tou
  • Project address: Ying-leetCode
  • Mumble: Mmmmm, swipe leetcode irregularly and it will be output as JS TS PY

Topic describes

Given an integer array nums and a target value target,

Find the two integers in the array where and are the target values.

And returns their array index.

You can assume that there is only one answer for each type of input.

However, you cannot reuse the same elements in this array.

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

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

So return [0, 1]

Their thinking

The first thing that comes to mind when I see the topic is bubbles, but since IT is serious to brush LeetCode, it is a little awkward to write bubbles, so is there a calculation method with lower time complexity? Thought for a moment just chose the HASH way, way of thinking is to define a data object, then the cyclic query array, and then to do a bit of course is that the current cycle Numbers as a key, the address as a value, inserted into the object, and then calculate the current target results with the current number of poor, to figure out whether this difference has been in object, if in, That means these two are the results, output, or continue the cycle.

JS version

/** * @param {number[]} nums * @param {number} target * @return {number[]} */
const twoSum = (nums, target) = > {
    const obj = {}
    for (let i = 0, len = nums.length; i < len; ++i) {
        const data = nums[i]
        const res = target - data
        if (res in obj) {
            return [obj[res], i]
        }
        obj[data] = i
    }
}
Copy the code

TS edition

interface objType {
    [propName: string] :number
}
/** * @param {number[]} nums * @param {number} target * @return {number[]} */ 
const twoSum = (nums: number[], target: number) :number[] | undefined= > {
    const obj: objType = {}
    for (let i: number = 0, len: number = nums.length; i < len; ++i) {
        const data: number = nums[i]
        const res: number = target - data
        if (res in obj) {
            return [obj[res], i]
        }
        obj[data] = i
    }
}
Copy the code

PY version

class Solution:
    """ :type arg1: List[int] :param nums: :type arg2: int :param target: :rtype: (List[int], None) :return: """
    def twoSum(self, nums: List[int], target: int) -> (List[int], None) :
        obj = {}
        for i, data in enumerate(nums):
            res = target - data
            if res in obj:
                return [obj[res], i]
            obj[data] = i
        return None
Copy the code

If you like to discuss technology, or have any comments or suggestions on this article, you are welcome to add yu Tou wechat friends to discuss. Of course, Yu Tou also hopes to talk about life, hobbies and things with you. You can also scan your wechat account to subscribe to more exciting content.