Advertisement
Guest User

Two sum - ChatGPT

a guest
Feb 16th, 2024
321
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.73 KB | Software | 0 0
  1. class Solution(object):
  2.    def twoSum(self, nums, target):
  3.        """
  4.       :type nums: List[int]
  5.       :type target: int
  6.       :rtype: List[int]
  7.       """
  8.        num_indices = {}
  9.  
  10.        # Iterate through the array
  11.        for i, num in enumerate(nums):
  12.            # Calculate the complement needed to reach the target
  13.            complement = target - num
  14.          
  15.            # Check if the complement exists in the dictionary
  16.            if complement in num_indices:
  17.                # Return the indices of the current element and its complement
  18.                return [num_indices[complement], i]
  19.      
  20.            # If the complement does not exist, store the index of the current element
  21.            num_indices[num] = i
  22.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement