go - Reduce array length -


One is trying to merge two string array. All duplicate elements should be removed in the resulting array. String {l: (str1) + len (Str2), cap (str1) + cap Str2)) k: = create (map [string] bool) i, s: = range str1 {if _, ok: = k [s] for; ! OK {c [i] = s k [s] = true}} for j, s: = grade str2 {if _, ok: = k [s]; ! OK {c [j [lane] (sr1)] = ss [s] = true}} return c}

test data

  str1: Strings {"a", "b"} str2: = [] string {"c", "d", "a"}  

output: "a "B", "C", "D" The length of the array "5"

I think the output is getting, but the array's Length should be 4 and not 5 . I understand why it prints 5 , but I want the output array of length 4 , there is no other way to merge two arrays.

Start with the length of zero and when you add element. For example,

  package main import "fmt" func MergeArrays (a1, a2 [] string) [] string {m: = make ([] string, 0, lane (a1) + For len (A2)): = {(string {a1, a2}}} _, s: = for category = (make [string] bool, len (a1) + len (a2)), Aa {if} k [s] {m = append (m, s) k [s] = true}} return m} func main () {a1: = [] string {" A "," b "} a2: = [] string {" c "," d "," a "} m: = merge array (a1, a2) fmt.println (len (m), m)}  

Output:

  4 [abcd]  

Comments