JS斩杀LeetCode(1):Two Sum

栏目: 编程工具 · 发布时间: 8年前

内容简介:JS斩杀LeetCode(1):Two Sum

题目:

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the  same element twice.

示例:

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

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

原题链接:

https://leetcode.com/problems/two-sum/#/description

解法①

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var twoSum = function(nums, target) {
    var result = [];
    for (var i = 0; i < nums.length; i++) {
        for (var j = i+1; j < nums.length; j++) {
            if (nums[i] + nums[j] === target && i !== j) {
                result[0] = i;
                result[1] = j;
                return result;
            }
        }
    }
    return result;
};

这种解法比较常规,时间复杂度为O(n²)。通过两个for循环遍历所有元素,当两元素之和等于target,且下标不等时,返回结果。

解法②

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var twoSum = function(nums, target) {
    var temp = [];
    for (var i = 0; i < nums.length; i++) {
        var cur = nums[i];
        if (temp[target - cur] !== undefined) {
            return [temp[target - cur], i];
        }
        temp[cur] = i;
    }
    return [];
};
这种解法相比第一种更高效,时间复杂度为O(n)。将数组值作为temp数组的下标,符合条件则返回结果。

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

iOS游戏编程之从零开始

iOS游戏编程之从零开始

李华明 / 2013-2 / 59.00元

《iOS游戏编程之从零开始:Cocos2d-x与cocos2d引擎游戏开发》是作者继《android游戏编程之从零开始》热销之后编写的又一本、基于cocos2d—x2.x和cocos2d—iphone版本,讲述ios平台游戏开发的新作。《iOS游戏编程之从零开始:Cocos2d-x与cocos2d引擎游戏开发》分为两个部分共11章,内容主要包括cocos2d—x引擎游戏开发的基础,常用的类、方法及......一起来看看 《iOS游戏编程之从零开始》 这本书的介绍吧!

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

html转js在线工具
html转js在线工具

html转js在线工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具