A small algorithm problem: the sum of two numbers

Time:2021-7-12

A small algorithm problem: the sum of two numbers

Specific requirements:
Given an integer array, a target value is specified. After adding two values in the integer array, the result is equal to the target value. Finally, the index values of these two values are returned

for instance:

number := []int{123,12,4,53, 66}
target := 16

12 + 4 = 16 in number 
The corresponding subscripts are number [1] and number [2]

There are probably two ways to write it

The first violent algorithm is to write two for loops and get the result by comparing two numbers

package main

import "fmt"

func main () {
  num := []int{12, 4, 6, 78, 9, 1, 66}
  target := 16

  for i := 0; i <= len(num) - 1; i++ {
    for j := 1; j <= len(num) - 1; j++ {
      if num[i] + num[j] == target {
        fmt.Println(i, j);
      }
    } 
  }
}
In this way, the efficiency is not too high. If there are a lot of data to be processed, it will be time-consuming

The second writing method: using hash search method

package main

import "fmt"

func main() {
   num := []int{12, 3, 4, 63, 45, 6, 8, 7, 89, 9}
   target := 16

   //Define a set
   hasTable := map[int]int{}

   //Cyclic treatment
   for key, val := range num {
       //If the search value already exists in the map, print out the result value
       if index, ok := hasTable[target - val]; ok {
           fmt.Println(index, key);
           break;
       }

       //If it doesn't exist, store the value in the map
       hasTable[val] = key
   }
}
This way of writing saves a layer of loops, and the code looks relatively concise. The query efficiency is also improved compared with the first one.

The second way is to save the value into the hash table, and then get the result by subtracting (target – n). The first time, the hastable must be empty, and then the value will be saved. In the second and N cycles, if the result can be obtained after target – N, the value has been saved before that.

A simple algorithm problem, mainly to practice the algorithm^_^

This work adoptsCC agreementReprint must indicate the author and the link of this article