1. Two Sum

Easy

Problem Description

1. Two Sum

Easy


Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

 

Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].

Example 2:

Input: nums = [3,2,4], target = 6
Output: [1,2]

Example 3:

Input: nums = [3,3], target = 6
Output: [0,1]

 

Constraints:

  • 2 <= nums.length <= 104
  • -109 <= nums[i] <= 109
  • -109 <= target <= 109
  • Only one valid answer exists.

 

Follow-up: Can you come up with an algorithm that is less than O(n2) time complexity?

Solutions

0001-two-sum.java

java
0001-two-sum.java
1class Solution { 2 public int[] twoSum(int[] nums, int target) { 3 for(int i=0;i<nums.length-1;i++){ 4 int complement=target-nums[i]; 5 for(int j=i+1;j<nums.length;j++){ 6 if (complement==nums[j]){ 7 return new int []{i,j}; 8 } 9 } 10 } 11 return new int[]{}; 12 } 13} 14

0001-two-sum.py

python
0001-two-sum.py
1class Solution: 2 def twoSum(self, nums: List[int], target: int) -> List[int]: 3 numMap = {} 4 n = len(nums) 5 6 for i in range(n): 7 complement = target - nums[i] 8 if complement in numMap: 9 return [numMap[complement], i] 10 numMap[nums[i]] = i 11 12 return [] # No solution found
LeetCode Practice