Analysis of force deduction problem - sum of two numbers

Analysis of force buckle problem

1. Sum of two numbers

Given an integer array nums and a target value target, please find the two integers with and as the target value in the array and return their array subscripts.

You can assume that each input will correspond to only one answer. However, the same element in the array cannot be used twice.


Given num = [2, 7, 11, 15], target = 9

Because nums[0] + nums[1] = 2 + 7 = 9

So [0, 1] is returned


Obviously, the solution of violence is a two-layer for loop search, and the time complexity is O(n^2).

I suggest you do these two before you do this topic

242. Valid acronyms This problem is to use an array as a hash table to solve the hash problem, 349. Intersection of two arrays This problem is to solve the hash problem by using set as a hash table.

For this problem, we need to use map. Let's look at the limitations of using array and set as hash method.

  • The size of the array is limited, and if there are few elements and the hash value is too large, it will cause a waste of memory space.
  • Set is a set, and the element in it can only be a key. For the question of the sum of two numbers, we should not only judge whether y exists, but also record the position of Y in the following table, because we need to return the following tables of x and y. So set doesn't work.

At this time, you need to select another data structure: map. Map is a storage structure of key value. You can use key to save values, and use value in the following table where values are saved.

In C + +, there are three types of map s:

mappingUnderlying implementationIs it orderlyCan values be repeatedCan I change the valueQuery efficiencyAddition and deletion efficiency
std::mapRed black treekey orderkey cannot be repeatedkey cannot be modifiedO(logn)O(logn)
std::multimapRed black treekey orderkey repeatablekey cannot be modifiedO(logn)O(logn)
std::unordered_mapHashtable key disorderkey cannot be repeatedkey cannot be modifiedO(1)O(1)

std::unordered_ The underlying implementation of map is hash table, and the underlying implementation of std::map and std::multimap is red black tree.

Similarly, the key s of std::map and std::multimap are also ordered (this question is often used as an interview question to investigate the understanding of the underlying language container). For more theoretical knowledge of hash tables, see You should know this about hash tables!.

The key order is not required in this topic. Select std::unordered_map is more efficient!

C + + Code:

class Solution {
    vector<int> twoSum(vector<int>& nums, int target) {
        std::unordered_map <int,int> map;
        for(int i = 0; i < nums.size(); i++) {
            auto iter = map.find(target - nums[i]);
            if(iter != map.end()) {
                return {iter->second, i};
            map.insert(pair<int, int>(nums[i], i));
        return {};

Other language versions


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


class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        for ind,num in enumerate(nums):
            hashmap[num] = ind
        for i,num in enumerate(nums):
            j = hashmap.get(target - num)
            if j is not None and i!=j:
                return [i,j]


func twoSum(nums []int, target int) []int {
    for k1, _ := range nums {
        for k2 := k1 + 1; k2 < len(nums); k2++ {
            if target == nums[k1] + nums[k2] {
                return []int{k1, k2}
    return []int{}
// Use map to solve problems and reduce time complexity
func twoSum(nums []int, target int) []int {
    m := make(map[int]int)
    for index, val := range nums {
        if preIndex, ok := m[target-val]; ok {
            return []int{preIndex, index}
        } else {
            m[val] = index
    return []int{}


use std::collections::HashMap;

impl Solution {
    pub fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> {
        let mut map = HashMap::with_capacity(nums.len());

        for i in 0..nums.len() {
            if let Some(k) = map.get(&(target - nums[i])) {
                if *k != i {
                    return vec![*k as i32,  i as i32];
            map.insert(nums[i], i);
        panic!("not found")


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


function twoSum(array $nums, int $target): array
    for ($i = 0; $i < count($nums);$i++) {
        // Calculate the remaining number
        $residue = $target - $nums[$i];
        // If there is a matching index, it returns index; if there is no index, it returns false
        $match_index = array_search($residue, $nums);
        if ($match_index !== false && $match_index != $i) {
            return array($i, $match_index);
    return [];

Tags: PHP Python Java C++ Algorithm

Posted on Thu, 16 Sep 2021 22:23:19 -0400 by matto