Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
LeetCode/two_sum
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
33 lines (27 sloc)
914 Bytes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 code: | |
class Solution: | |
def twoSum(self, nums, target): | |
""" | |
:type nums: List[int] | |
:type target: int | |
:rtype: List[int] | |
""" | |
search_dict={} | |
for i in range(len(nums)): | |
search_dict[int(nums[i])]=i | |
for i in range(len(nums)-1): | |
value=int(target-nums[i]) | |
if value in search_dict.keys(): | |
j=search_dict[value] | |
if j==i: | |
continue | |
return [i,j] | |
return None | |
Solution: | |
https://leetcode.com/problems/two-sum/solution/ |