合併2個數組爲1個無重複元素的有序數組--Go對比Python

Go實現:數組

 1 package main  2 
 3 import (  4     "fmt"
 5     "sort"
 6 )  7 
 8 func main() {  9     var a = []int{1, 6, 45, 2, 9, 15, 7} 10     var b = []int{2, 80, 9, 67, 52, 15, 100, 99} 11     c := sumArr(a, b) 12     fmt.Println("合併後的數組爲") 13  fmt.Println(c) 14     d := remArr(c) 15     fmt.Println("合併、去重後的數組爲") 16  fmt.Println(d) 17     e := sortArr(d) 18     fmt.Println("合併、去重、排序後的數組爲") 19  fmt.Println(e) 20 } 21 
22 func sumArr(a, b []int) []int { 23  var c []int 24     for _, i := range a{ 25         c = append(c, i) 26  } 27     for _, j := range b{ 28         c = append(c, j) 29  } 30     return c 31 } 32 
33 func remArr(c []int) []int { 34     d := make([]int, 0) 35     tempMap := make(map[int]bool, len(c)) 36     for _, e := range c{ 37         if tempMap[e] == false{ 38             tempMap[e] = true 39             d = append(d, e) 40  } 41  } 42     return d 43 } 44 
45 func sortArr(e []int) []int { 46  sort.Ints(e[:]) 47     return e 48 }

Python實現:app

 1 a = [1, 6, 45, 2, 9, 15, 7]  2 b = [2, 80, 9, 67, 52, 15, 100, 99]  3 c = a + b  4 
 5 # 方法一:
 6 d = set(c)  7 print(sorted(d))  8 
 9 # 方法二:
10 e = [] 11 for i in c: 12     if i not in e: 13  e.append(i) 14         continue
15 print(sorted(e))
相關文章
相關標籤/搜索