leetcode-pp / 91alg-5-daily-check

91 天学算法第五期打卡
55 stars 14 forks source link

【Day 19 】2021-09-28 - 两数之和 #34

Open azl397985856 opened 3 years ago

azl397985856 commented 3 years ago

两数之和

入选理由

暂无

题目地址

https://leetcode-cn.com/problems/two-sum

前置知识

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/two-sum 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

alwaysbest commented 3 years ago

class Solution { public int[] twoSum(int[] nums, int target) { Map<Integer, Integer> map = new HashMap<>((int) ((float) nums.length / 0.75F + 1.0F)); for (int i = 0; i < nums.length; i++) { if (map.containsKey(target - nums[i])) { return new int[]{map.get(target - nums[i]), i}; } map.put(nums[i], i); } throw new IllegalArgumentException("No two sum value"); } }

last-Battle commented 3 years ago

思路

关键点

代码

C++ Code:


class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> res;
        unordered_map<int, int> um;

        for (int i = 0; i < nums.size(); ++i) {
            if (um.find(target - nums[i]) != um.end()) {
                return vector<int>{um[target - nums[i]], i};
            }

            um[nums[i]] = i;
        }

        return res;
    }
};

复杂度分析

令 n 为数组长度。

yanglr commented 3 years ago

思路

可以用双指针或哈希表来做。

方法1: 双指针法

先固定一个, 找另一个。发现第一次出现nums[i] + nums[j] == target就返回结果.

代码

实现语言: C++

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {        
        vector<int> res(2);
        // 双指针, 先固定一个
        for (int i = 0; i < nums.size(); i++)
        {
            for (int j = i + 1; j < nums.size(); j++)
            {
                if (nums[i] + nums[j] == target)
                {
                    res[0] = i;
                    res[1] = j;
                    return res;
                }
            }
        }
        return res;
    }
};

复杂度分析:

方法2: 哈希表

在哈希表中找 target - 当前循环变量i对应的那个数。哈希表存储每个数对应的下标(映射: value -> index)。

代码

实现语言: C++

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int, int> dict; // map: value -> index
        vector<int> res(2);
        for (int i = 0; i < nums.size(); i++)
        {
            int query = target - nums[i];
            if (dict.find(query) == dict.end())
                dict[nums[i]] = i;
            else
            {
                res[0] = dict[query]; // 如果能找到, query会出现在nums[i]的前面(index of query <= i)
                res[1] = i;
                return res;
            }
        }
        return {};
    }
};

复杂度分析:

ZhuMengCheng commented 3 years ago

思路,判断差值,存储 hash判断是否存在

var twoSum = function(nums, target) {
    // 定义map存储差值    
    let map = new Map();
    for(let i =0;i<nums.length ;i++){
        // 计算差值
        const value = target - nums[i];
        if(map.has(value)){
            // 存在即返回当前存储差值的下标,和当前值的下标
            return [map.get(value), i];
        }else{
            // 存储所有差值的下标
            map.set(nums[i], i)
        }
    }
};

// 空间复杂:O(N) // 时间复杂:O(N)

yachtcoder commented 3 years ago
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        m = {}
        for i, n in enumerate(nums):
            if target - n in m:
                return [m[target - n], i]
            m[n] = i
        return [-1, -1]
BpointA commented 3 years ago

思路

哈希表+遍历数组。

Python3代码

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        has={}
        for i in range(len(nums)):
            if target-nums[i] in has:
                return [has[target-nums[i]],i]
            has[nums[i]]=i
        return []

复杂度

时间复杂度:O(n) ,遍历数组,对遍历过的数查询哈希表

空间复杂度:O(n) ,哈希表最长为数组长度

Kirito1017 commented 3 years ago

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        int[] res = new int[2];

        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(target - nums[i])) {
                res[0] = map.get(target - nums[i]);
                res[1] = i;
                return res;
            }
            map.put(nums[i], i);
        }

        return res;
    }
}
yibenxiao commented 3 years ago

【Day 19】两数之和

思路

遍历整个列表,当前值为x,寻找y=target-x

代码

class Solution:
    def twoSum(self,nums,target):
        n = len(nums)
        for x in range(n):
            a = target - nums[x]
            if a in nums:
                y = nums.index(a)
                if x == y: 
                    continue
                else:
                    return x,y 

复杂度

时间复杂度:O(N*LogN)

空间复杂度:O(1)

kidexp commented 3 years ago

thoughts

Hashmap key是值 value存下标,然后遍历一遍,看sum-nums[i]在不在之前的hashmap里面,在就返回,不在就加入hashmap继续

code

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        num_index_map = {}
        for i, num in enumerate(nums):
            if (target-num) in num_index_map:
                return [num_index_map[target - num], i]
            num_index_map[num] = i

complexity

time O(n) Space O(n)

wangzehan123 commented 3 years ago

public class Solution {
    public int[] twoSum(int[] numbers, int target) {
        HashMap<Integer,Integer> map = new HashMap<>();

        for (int i = 0; i < numbers.length; i++) {
            if (map.get(numbers[i]) != null) {
                int[] result = {map.get(numbers[i]), i};
                return result;
            }
            map.put(target - numbers[i], i);
        }

        int[] result = {};
        return result;
    }
}

复杂度分析

令 n 为数组长度。

jaysonss commented 3 years ago

思路

构建一个哈希表dict,遍历数组,尝试获取补数索引

关键点˜

代码

Java Code:

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for(int i=0;i<nums.length;i++){
            int v = target - nums[i];
            Integer idx = map.get(v);
            if(idx != null){
                return new int[]{i,idx};
            }else{
                map.put(nums[i],i);
            }
        }
        return new int[0];
    }
}

复杂度分析

st2yang commented 3 years ago

思路

代码

复杂度

Okkband commented 3 years ago
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {        
        vector<int> res(2);
        for (int i = 0; i < nums.size(); i++)
        {
            for (int j = i + 1; j < nums.size(); j++)
            {
                if (nums[i] + nums[j] == target)
                {
                    res[0] = i;
                    res[1] = j;
                    return res;
                }
            }
        }
        return res;
    }
};

复杂度分析: 时间复杂度: O(n^2) 空间复杂度: O(1)

zjsuper commented 3 years ago

idea: Using dic to store the value and index Time and space: O(N)

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        dic = {}
        for i in range(len(nums)):
            if target -nums[i] not in dic:
                dic[nums[i]] = i
            else:
                return [dic[target -nums[i]],i]
        return None
taojin1992 commented 3 years ago

Plan:

bruteforce: two pointers O(n^2) time with O(1) space

optimized:
traverse, search for target - val in map, if no then insert into map
val - index map

n = nums.length
Time: O(n)
Space: O(n) 

Code:

class Solution {
    // bruteforce
    public int[] twoSum1(int[] nums, int target) {
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[i] + nums[j] == target) {
                    return new int[]{i, j};
                }
            }
        }
        return new int[]{};
    }

    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> valIndexMap = new HashMap<>();
        for (int i = 0 ; i < nums.length; i++) {
            int val = nums[i];
            if (valIndexMap.containsKey(target - val)) {
                return new int[]{valIndexMap.get(target - val), i};
            } 
            valIndexMap.put(val, i);
        }
        return new int[]{};
    }
}
pangjiadai commented 3 years ago

思路:Hashmap

空间换时间

Python3

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        hashmap = {}
        for index, num in enumerate(nums):
            if target - num in hashmap:
                return [index, hashmap[target-num]]
            hashmap[num] = index

复杂度

leungogogo commented 3 years ago

LC1. Two Sum

Method 1. Map

Main Idea

Use a map to record the number we've seen so far, if map.get(k - nums[i]) != null, then we've found the pair.

Code

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int n = nums.length;
        // value -> index
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < n; ++i) {
            if (map.containsKey(target - nums[i])) {
                return new int[] {map.get(target - nums[i]), i};
            }

            map.put(nums[i], i);
        }

        return new int[] {-1, -1};
    }
}

Complexity Analysis

Time: O(n)

Space: O(n)

Method 2. Sorting + 2 Ptrs

Main Idea

Sort the array, then perform two pointers find the pair:

Note that we need to return the index, and if we sort the input then we no longer have access to the indices, so we need to create an index array arr to sort.

Code

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Integer arr[] = new Integer[nums.length];
        for (int i = 0; i < nums.length; ++i) {
            arr[i] = i;
        }

        Arrays.sort(arr, (n1, n2) -> nums[n1] - nums[n2]);

        int l = 0, r = nums.length - 1;
        while (l < r) {
            if (nums[arr[l]] + nums[arr[r]] == target) {
                return new int[] {arr[l], arr[r]};
            } else if (nums[arr[l]] + nums[arr[r]] < target) {
                ++l;
            } else {
                --r;
            }
        }

        return new int[] {-1, -1};
    }
}

Complexity Analysis

Time: O(nlogn)

Space: O(n)

pzl233 commented 3 years ago

思路

用HashMap存储数组中每个元素和相对的index. 在遍历数组的同时寻找是否存在一个值可以使当前值 + 它 = target

代码

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        int[] result = new int [2];
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(target - nums[i])) {
                result[0] = i;
                result[1] = map.get(target - nums[i]);
                return result;
            }
            map.put(nums[i], i);
        }
        return result;
    }
}

复杂度分析

时间复杂度: O(n) 空间复杂度: O(n)

mmboxmm commented 3 years ago

思路

第一题

代码

fun twoSum(nums: IntArray, target: Int): IntArray {
  val map = mutableMapOf<Int, Int>()
  for ((index, num) in nums.withIndex()) {
    if (map.containsKey(num)) return intArrayOf(map[num]!!, index)
    map[target - num] = index
  }
  return intArrayOf()
}

复杂度

pophy commented 3 years ago

思路

Java Code

    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap();
        for (int i=0; i<nums.length; i++) {
            int num = nums[i];
            if (map.containsKey(target - num)) {
                return new int[]{map.get(target - num), i};
            }
            map.put(num, i);
        }
        return null;
    }

时间&空间

erik7777777 commented 3 years ago
class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(target - nums[i])) {
                return new int[]{map.get(target - nums[i]), i};
            }
            map.put(nums[i], i);
        }
        return new int[]{-1, -1};
    }
}
q815101630 commented 3 years ago

Thoughts

利用哈希表,可以把当前数字存进表,遍历时,如果target-v在表内,说明之前存过,就return

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        table = {}
        for i,v in enumerate(nums):
            if target-v in table:   # diff in table
                return (i,table[target-v])    #
            table[v]=i

Time: O(n) Space: O(n)

cicihou commented 3 years ago

class Solution:
    def twoSum(self, nums, target: int) -> list:
        cache = {}
        for i in range(len(nums)):
            if nums[i] not in cache:
                cache[target-nums[i]] = i
            else:
                return [cache[nums[i]], i]
MonkofEast commented 3 years ago

1. Two Sum

Click Me

Algo

INSIDE DNA

Code

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        adict = {}        
        for idx, n in enumerate(nums):
            if n in adict: return list((adict[n], idx))
            adict[target - n] = idx

Comp

T: O(N)

S: O(N)

xj-yan commented 3 years ago
class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++){
            if (map.containsKey(target - nums[i])) {
                return new int[]{map.get(target - nums[i]), i};
            }else {
                map.put(nums[i], i);
            }
        }
        return null;
    }
}

Time Complexity: O(n) Space Complexity: O(n)

nonevsnull commented 3 years ago

思路

AC

代码

//use hashmap
class Solution {
    public int[] twoSum(int[] nums, int target) {
        //create map to save [visited, index]
        HashMap<Integer, Integer> map = new HashMap<>();
        //traverse nums
        for(int i = 0;i < nums.length;i++){
            if(map.containsKey(target - nums[i])){
                return new int[]{map.get(target - nums[i]), i};
            } else{
                map.put(nums[i], i);
            }
        }
        return new int[2];
    }
}

复杂度

//use hashmap time: 需要遍历nums,O(N) space: 需要hashmap,O(N)

ruohai0925 commented 3 years ago

前置知识

公司

思路

关键点

代码

Python3 Code:


# Hashtable 2
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        hashtable = dict()
        for i, num in enumerate(nums):
            if target - num in hashtable:
                return [hashtable[target - num], i]
            hashtable[num] = i
        return []

# Similar to hashtable 2
def two_sum(nums, target):
    dct = {}
    for i, n in enumerate(nums):
        cp = target - n
        if cp in dct:
            return [dct[cp], i]
        else:
            dct[n] = i

复杂度分析

令 n 为数组长度。

chakochako commented 3 years ago
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        d = {}

        for i, v in enumerate(nums):
            if (target - v) in d:
                return [d[target - v],i]
            else:
                d[v] = i
falconruo commented 3 years ago

思路:

使用hashmap存放数组的值和indices, 循环判断数组的每一个元素,如果target - nums[i]在hashmap中则nums[i]必在, 返回两者的indices

复杂度分析:

时间复杂度: O(n), n为数组nums的元素个数 空间复杂度: O(n), hashmap空间

代码(C++):

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        map<int, int> used;
        int n = nums.size();

        for (int i = 0; i < n; ++i) {
            if (used.count(target - nums[i]))
                return {used[target - nums[i]], i};
            used[nums[i]] = i;
        }

        return {};
    }
};
heyqz commented 3 years ago

code

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        hashmap = {}
        for i, num in enumerate(nums):
            diff = target - num
            if diff not in hashmap:
                hashmap[num] = i
            else:
                return [hashmap[diff], i]

complexity

time: O(N) space: O(N)

JiangyanLiNEU commented 3 years ago

Idea

Implement (Runtime=O(nlogn) Space=O(n))

class Solution(object):
    def twoSum(self, nums, target):
        # dic: num: cur_index
        dic = defaultdict(list)
        for index, num in enumerate(nums):
            dic[num].append(index)
        # order nums, two pointer to get right numbers
        nums.sort()

        first = 0
        second = len(nums)-1

        while nums[first] + nums[second] != target:
            if nums[first] + nums[second] > target:
                second -= 1
            elif nums[first] + nums[second] < target:
                first += 1
            else:
                break
        # return index with the help of dic
        if nums[first] == nums[second]:
            return dic[nums[first]]
        return [dic[nums[first]][0], dic[nums[second]][0]]
comst007 commented 3 years ago

1. 两数之和


思路

哈希表。 通过哈希表记录当前已经出现的数及其下表。当遍历到每个数组元素cur_num时, 查一下sum - cur_num在不在哈希表中。

如果在说明存在两个数。否则不存在。

代码

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int, int> h_cnt;
        int n, ii, jj;
        n = nums.size();
        if(n < 2) return vector<int>();

        vector<int> ans;
        h_cnt[nums[0]] = 0;
        for(ii = 1; ii < n; ++ ii){
            if(h_cnt.count(target - nums[ii])){
                jj = h_cnt[target - nums[ii]];
                ans.push_back(ii);
                ans.push_back(jj);
                break;
            }
            h_cnt[nums[ii]] = ii;
        }
        return ans;

    }
};

复杂度分析

n 为数组元素个数。

potatoMa commented 3 years ago

思路


哈希表储存差值

代码


JavaScript Code

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var twoSum = function(nums, target) {
    const map = new Map();
    for (let i = 0;i < nums.length;i++) {
        const num = nums[i];
        if (!map.has(target - num)) {
            map.set(num, i);
            continue;
        }
        return [map.get(target - num), i];
    }
};

复杂度分析


时间复杂度:O(N)

空间复杂度:O(N)

yingliucreates commented 3 years ago

link:

https://leetcode.com/problems/two-sum/

代码 Javascript

const twoSum = function (nums, target) {
  let hash = {};

  for (let i = 0; i < nums.length; i++) {
    const n = nums[i];
    if (hash[target - n] !== undefined) {
      return [hash[target - n], i];
    }
    hash[n] = i;
  }
  return [];
};

复杂度分析

时间空间皆为 O(n)

tongxw commented 3 years ago

思路

哈希表记忆

代码

 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var twoSum = function(nums, target) {
    const map = new Map();
    let i = 0;
    let j = -1;
    for (i=0; i<nums.length; i++) {
      if (map.has(target - nums[i])) {
        j = map.get(target - nums[i]);
        break;
      } else {
        map.set(nums[i], i);
      }
    }

    return j == -1 ? [] : [i, j];
};
Menglin-l commented 3 years ago

思路:

用hashmap来做,key为值,value为索引,遍历数组,同时寻找target - num[i],找到就返回。


代码部分:

class Solution {
    public int[] twoSum(int[] nums, int target) {
        HashMap<Integer, Integer> list = new HashMap<>();

        for (int i = 0; i < nums.length; i ++) {

            if (list.containsKey(target - nums[i])) {
                return new int[]{i, list.get(target - nums[i])};
            }

            list.put(nums[i], i); 
        }
        return new int[]{};
    }
}

复杂度:

Time: O(N)

Space: O(N)

pan-qin commented 3 years ago

idea: use a hashmap to tell whether target-nums[i] exists. If yes, return; else save the value and index into the map. Time: O(n) Space: O(n)

class Solution {
    public int[] twoSum(int[] nums, int target) {
        HashMap<Integer,Integer> map = new HashMap<>();
        int[] res = new int[2];
        for(int i=0;i<nums.length;i++) {
            if(map.containsKey(target-nums[i])) {
                res[0]=map.get(target-nums[i]);
                res[1]=i;
                return res;
            }
            else {
                map.put(nums[i],i);
            }
        }
        return res;
    }
}
skinnyh commented 3 years ago

Note

Scan the list and use a dict to record each num and its idx. If (target - current_num) is in the dict then we find the result pair.

Solution

def twoSum(self, nums: List[int], target: int) -> List[int]:
    d = {}
    for idx, n in enumerate(nums):
        if (target - n) in d:
            return [d[target - n], idx]
        d[n] = idx

Time complexity: O(N)

Space complexity: O(N)

itsjacob commented 3 years ago

Intuition

Implementation

class Solution
{
public:
  vector<int> twoSum(vector<int> &nums, int target)
  {
    std::unordered_map<int, int> aMap;
    std::vector<int> res;
    for (int ii = 0; ii < nums.size(); ii++) {
      if (aMap.count(target - nums[ii]) > 0) {
        res.push_back(ii);
        res.push_back(aMap[target - nums[ii]]);
        break;
      } else {
        aMap.emplace(nums[ii], ii);
      }
    }
    return res;
  }
};

Complexity

thinkfurther commented 3 years ago

思路

用dict记录每一个数的位置,然后判断target减去这个数是否在dict里

代码

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        hashmap = dict()
        for idx, value in enumerate(nums):
            hashmap[value] = idx            
        for idx, value in enumerate(nums):
            j = hashmap.get(target - value)
            if j != None and idx != j:
                return [idx,j]

复杂度

时间复杂度 :O(N)

空间复杂度:O(N)

zol013 commented 3 years ago

思路:遍历数组,查看target - nums[i] 在不在hashmap里面, 如果在的话 返回, 不在的话把nums[i]以及index记录在hashmap。\

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        hashmap = {}
        for i in range(len(nums)):
            complement = target - nums[i]
            if complement in hashmap:
                return [i, hashmap[complement]]
            hashmap[nums[i]] = i

Time Complexity: O(n) Space Complexity: O(n)

ZiyangZ commented 3 years ago
class Solution {
    public int[] twoSum(int[] nums, int target) {  
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (!map.containsKey(target - nums[i])) {
                map.put(nums[i], i);
            } else {
                return new int[] {i, map.get(target - nums[i])};
            }
        }
        return null;
    }
}
joeytor commented 3 years ago

思路

一次遍历, 每次遇到一个数, 先判断 target - num 在不在哈希表中, 如果在的话说明找到了那两个整数, 返回这个数 和 target - num 的 index

如果 n 不在 d 中, 把 d[n] = i 添加到 dict 中

代码

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        d = dict()
        for i,n in enumerate(nums):
            if (target-n) in d:
                return [i, d[target-n]]
            if n not in d:
                d[n] = i

复杂度

N 是 nums 长度

时间复杂度: O(N) 一次遍历数组

空间复杂度: O(N) 哈希表最坏情况是 O(N) 级别复杂度

kennyxcao commented 3 years ago

1. Two Sum

Intuition

Code

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
const twoSum = function(nums, target) {
  const lookup = {};
  for (let i = 0; i < nums.length; ++i) {
    const j = lookup[target - nums[i]];
    if (j != null) return [i, j];
    lookup[nums[i]] = i;
  }
  return [-1, -1];
};

Complexity Analysis

Yufanzh commented 3 years ago

Intuition

Two sum can be solved by storing the value in hash map which will make lookup much faster.

Algorithm in Python3

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        hashMap = collections.defaultdict(int)

        for i, num in enumerate(nums):
            if target-num in hashMap:
                return [i, hashMap[target-num]]
            else:
                hashMap[num] = i
        return -1

Complexity Analysis

shixinlovey1314 commented 3 years ago

Title:1. Two Sum

Question Reference LeetCode

Solution

Use a map to store the value and its index, while iterating the array, keep on checking if the counter part has been in the map already, and return results if so.

Code

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        std::map<int, int> mapper;
        vector<int> result;

        for (int i = 0; i < nums.size(); i++) {
            int delta = target - nums[i];
            if (mapper.count(delta)) {
                result.push_back(mapper[delta]);
                result.push_back(i);
                break;
            }

            mapper[nums[i]] = i;
        }

        return result;
    }
};

Complexity

Time Complexity and Explanation

O(n), need to visit each item once

Space Complexity and Explanation

O(n), used to store in map.

BlueRui commented 3 years ago

Problem 1. Two Sum

Algorithm

Complexity

Code

Language: Java

public int[] twoSum(int[] nums, int target) {
    int[] result = new int[2];
    // key is nums[i], value is index i
    Map<Integer, Integer> map = new HashMap<>();
    for (int i = 0; i < nums.length; i++) {
        if (map.containsKey(target - nums[i])) {
            result[0] = map.get(target - nums[i]);
            result[1] = i;
            return result;
        }
        map.put(nums[i], i);
    }
    return null;
}
james20141606 commented 3 years ago

Day 19: 1. Two Sum (hashtable, two pointers)

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        dict = {}
        for i in range(len(nums)):
            if nums[i] in dict.keys():
                return [i,dict[nums[i]]]
            else:
                dict[target-nums[i]] = i
Mahalasu commented 3 years ago

思路

经典题,用hashmap

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        seen = {}
        for idx in range(len(nums)):
            diff = target - nums[idx]
            if diff in seen:
                return [seen[diff], idx]
            else:
                seen[nums[idx]] = idx

        return []

T: O(N) S: O(N)

naivecoder-irl commented 3 years ago

思路

哈希表,查询到结果则返回,查询不到则插入。

代码

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++){
            int diff = target - nums[i]; //key point
            if (map.containsKey(diff)){
                return new int[]{map.get(diff), i};
            }
            map.put(nums[i], i);
        }
        return null;
    }
}

复杂度分析