leetcode_Two sum
2017-05-16 12:32
381 查看
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:
My solution:
lennum = int(input("the length of num:"))
target = int(input("目标为:"))
i = 0
num = []
while i<lennum:
print("第 ", i, "个数为:")
n = int(input())
num.append(n)
i=i+1
print(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]
"""
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 = 0
num = []
while i<lennum:
print("第 ", i, "个数为:")
n = int(input())
num.append(n)
i=i+1
print(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]
"""
相关文章推荐
- [leetcode] Two Sum
- LeetCode Two Sum
- leetcode 1. Two Sum (C语言)12
- LeetCode-1. Two Sum
- [Leetcode]Two Sum
- [leetcode] 1. Two Sum
- leetcode-Two Sum[题解]
- [Leetcode]_1 Two Sum
- Leetcode之Two Sum
- Leetcode: Two Sum
- leetcode:Two Sum
- [LeetCode] Two Sum [17]
- [Leetcode 1, Medium] Two sum
- [Leetcode] Two Sum
- LeetCode 1 - Two Sum
- leetcode 1. Two Sum
- [LeetCode]Two Sum
- leetcode-1.Two Sum
- 从0开始的LeetCode生活—001-Two Sum
- LeetCode Practice_1 Two Sum