Leetcode
  • Leetcode
  • 1. Two Sum
  • 7. Reverse Integer
  • 9. Palindrome Number
  • 13. Roman to Integer
  • 20. Valid Parentheses
  • 21. Merge Two Sorted Lists
  • 26. Remove Duplicates from Sorted Array
  • 27. Remove Element
  • 28. Implement strStr()
  • 35. Search Insert Position
  • 53. Maximum Subarray
  • 58. Length of Last Word
  • 66. Plus One
  • 876. Middle of the Linked List
  • 67. Add Binary
  • 69. Sqrt(x)
  • 83. Remove Duplicates from Sorted List
  • 14. Longest Common Prefix
  • 70. Climbing Stairs
  • 100. Same Tree
  • 101. Symmetric Tree
  • 104. Maximum Depth of Binary Tree
  • Untitled
Powered by GitBook
On this page

1. Two Sum

PreviousLeetcodeNext7. Reverse Integer

Last updated 6 years ago

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].

Solution:

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        record = {} # to record if show before
        for i in range(len(nums)):
            if target-nums[i] in record: # if show before
                return [record[target-nums[i]], i]
            else:
                record[nums[i]] = i
https://leetcode.com/problems/two-sum/