1 two sum


title: Two Sum
tags:
- two-sum
- simple
- hash
- No.1
- integer


Problem

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

Brute-Force

Brute-Force runs in O(n^2):

class Solution {
    public int[] twoSum(int[] nums, int target) {
        // O(n^2)
        for (int i=0; i

Twice Hash

Hash twice: First takes O(n) to build HashMap. Second to search the complement O(n) times in O(1):

import java.util.*;

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map val_loc = new HashMap();
        
        // O(n)
        for (int i=0; i

Once Hash

Search the existed elements in table while insert new pairs to it. Thus loop one time in O(n):

import java.util.*;

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map val_loc = new HashMap();
        
        // O(n)
        for (int i=0; i

你可能感兴趣的:(1 two sum)