leetcode_Two sum

来源:互联网 发布:vue.js 2.0 教程下载 编辑:程序博客网 时间:2024/06/01 08:31
Problem:

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].
My solution:

lennum = int(input("the length of num:"))target = int(input("目标为:"))i = 0num = []while i<lennum:    print("第 ", i, "个数为:")    n = int(input())    num.append(n)    i=i+1print(num)for j in range(len(num)):    for k in range(j+1,len(num)):        if(num[j]+num[k]==target):            print("j:", j, "k:", k)            break
My solution could run but the time was exceeded. I found a proper solution and its time was accepted.The code was :

class Solution:    def twoSum(self, nums, target):        map = {}        for index,num in enumerate(nums):            if target - num in map:                return [map[target - num], index]            map[num] = index        """        :type nums: List[int]        :type target: int        :rtype: List[int]        """        



原创粉丝点击