1. Two Sum
Description of the Problem
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 <= 10^4-10^9 <= nums[i] <= 10^9-10^9 <= target <= 10^9- Only one valid answer exists.
Follow-up: Can you come up with an algorithm that is less than \(O(n^2)\) time complexity?
Solution
Tags: HashMap
Explanation
if num[i]+num[j]==target then return [i,j];
<===>
if num[i]==target-num[j] then return [i,j];
Code (Rust)
#![allow(unused)] fn main() { use std::collections::HashMap; impl Solution { pub fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> { let mut hashMap = HashMap::new(); for i in 0..nums.len(){ let complement = target - nums[i]; if hashMap.contains_key(&complement){ return vec![ i as i32 , hashMap[&complement] as i32 ]; } hashMap.insert(nums[i], i); } return vec![]; } } }
Code (Java)
import java.util.HashMap;
public class Solution_2 {
public int[] twoSum(int [] nums, int target){
// It stores (num->index)
HashMap <Integer,Integer> hashmap = new HashMap();
for(int i = 0; i < nums.length; i++){
int complement = target - nums[i];
if ( hashmap.containsKey(complement) ){
return new int[] { hashmap.get(complement), i};
}
hashmap.put(nums[i], i);
}
return null;
}
}
Complexity
- n is length of the array
Time complexity:
- \( T(n) = O(n) \)
- Assume hashMap get/put use constant time
Auxiliary Space:
- \( S(n) = O(2n) \)
- It store at most 2n (key and value) elements in HashMap