leetcode 1 两数之和

https://leetcode-cn.com/problems/two-sum/

暴力,复杂度n的平方

var twoSum = function(nums, target) {
    let arr = []
    for (let i = 0; i < nums.length;i++) {
        for (let j = i + 1; j < nums.length;j++) {
            if (nums[i] + nums[j] === target) {
                arr.push(i)
                arr.push(j)
            }
        }
    }
    return arr;
};

复杂度2n

var twoSum = function (nums, target) {
    let map = new Map();
    let arr = new Array();
    for (let i = 0; i < nums.length; i++) {
        map.set(nums[i], i)
    }
    for (let i = 0; i < nums.length; i++) {
        if (map.has(target - nums[i]) && map.get(target - nums[i]) !== i) {
            arr.push(i,map.get(target - nums[i]));
            return arr;
        }
    }
}
posted @ 2019-09-08 19:02  樱风凛  阅读(127)  评论(0编辑  收藏  举报