美文网首页
LeetCode:在一个整型数组中找到和为目标数字的两个元素的索

LeetCode:在一个整型数组中找到和为目标数字的两个元素的索

作者: 前端艾希 | 来源:发表于2019-07-09 19:58 被阅读0次

描述

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.

Example:

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

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

我的解决办法

遍历数组,求出目标数字与数组元素的差值diff,然后在数组中找到diff,返回其index

代码如下

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        temp = ''
        for index in range(len(nums)):
            diff = target - nums[index]
            for index_another in range(index+1, len(nums)):
                if nums[index_another] == diff:
                    temp = index_another
                    return [index, temp]
        return None

算法评估

Runtime: 3416 ms, faster than 28.78% of Python online submissions for Two Sum.
Memory Usage: 12.7 MB, less than 63.87% of Python online submissions for Two Sum.

参考算法

// python3
class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        dict = {}
        for i in range(len(nums)):
            if target-nums[i] not in dict:
                dict[nums[i]]=i
            else:
                return [dict[target-nums[i]],i]
                
// JavaScript
const twoSum = function(nums, target) {
    const comp = {};
    for(let i=0; i<nums.length; i++){
        if(comp[nums[i] ]>=0){
            return [ comp[nums[i] ] , i]
        }
        comp[target-nums[i]] = i
    }
};
## 参考链接
转载自:[https://leetcode.com/problems/two-sum/](https://leetcode.com/problems/two-sum/)

相关文章

  • LeetCode:在一个整型数组中找到和为目标数字的两个元素的索

    描述 Given an array of integers, return indices of the two ...

  • 2019-02-02 Day 28

    1.二分查找来源 LeetCode给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target...

  • 算法----两数之和

    给定一个数组,一个目标值,请在数组中找到和为目标值的两个数字,并返回他们的数组下标。 你可以假设每种输入只会对应一...

  • 二分查找

    目标:快速在数组中找到一个元素。 假设您有一个数组,并且您想确定某个特定数字是否在该数组中,如果是,那么返回索引。...

  • iOS常见算法1:2Sum问题(Swift语言实现)

    给一个整型数组和一个目标值,判断数组中是否有两个数字之和等于目标值分析:(1)如果每次选中一个数,然后遍历整个数组...

  • LeetCode - 0001 -Two Sum

    题目概要 在序列中找到和为特定值的两个元素的索引。 原题链接 LeetCode - Two Sum 解题思路 先将...

  • LeetCode 每日一题 [23] 搜索插入位置

    LeetCode 搜索插入位置 [简单] 给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标...

  • 2Sum算法

    给一个整型数组和一个目标值,判断数组中是否有两个数字之和等于目标值。 这道题是传说中经典的 “2Sum”,我们已经...

  • 704. 二分查找(Python)

    题目 难度:★☆☆☆☆类型:数组 给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target...

  • 跳跃游戏1&2

    LeetCode 55. Jump Game一个数组存储了非负整型数据,数组中的第i个元素nums[i],代表了可...

网友评论

      本文标题:LeetCode:在一个整型数组中找到和为目标数字的两个元素的索

      本文链接:https://www.haomeiwen.com/subject/akwfkctx.html