leetCode Series 1, two numbers

Two numbers and

1, two numbers

Description: 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.


Interpretations three kinds of problem solution

1, using brute, Looking double cycle twice, each data is traversed, as shown in FIG codes, a first layer traversed to find the remaining number, and then use a second layer traversal cycle (note that from the current i + 1 start, otherwise there may exist the same index value), then return directly to exit the loop after the find, and this method can clearly know i <j.

2, the object using object data storage, the data is first stored into the map a value key, the index index is value, which then has to traverse, the remaining results found, if present in the subject and not equal to i, then that found exit, but be careful in small to large sort to exit.

3, the principle above, but also use the data structure of map data storage, the data is first stored into the map, and then you can look directly once traversed.

var twoSum = function(nums, target) {
    // 暴力解决
    // for (let i = 0; i < nums.length; i++) {
    //     let left = target - nums[i];
    //     for (let j = i + 1; j < nums.length; j++) {
    //         if (nums[j] === left) {
    //             return [i, j]
    //         }
    //     }
    // }
    //使用map实现
    // let map = {};
    // for (let i = 0; i < nums.length; i++) {
    //     map[nums[i]] = i;
    // }
    // for (let i = 0; i < nums.length; i++) {
    //     let left = target - nums[i];
    //     if (map[left] && map[left] !== i) {
    //         return [map[left], i].sort((a, b) => a - b);
    //     }
    // }

    // Map
    let map = new Map();
    for (let i = 0; i < nums.length; i++) {
        map.set(nums[i], i);
    }
    for (let i = 0; i < nums.length; i++) {
        let left = target - nums[i];
        if (map.get(left) && map.get(left) !== i) {
            return [map.get(left), i].sort((a, b) => a - b);
        }
    }
};

Hope serious learning algorithm, every day a question common development and progress.

Published 19 original articles · won praise 58 · views 50000 +

Guess you like

Origin blog.csdn.net/cyg_l02/article/details/105353542