题解 | #三数之和#
三数之和
https://www.nowcoder.com/practice/345e2ed5f81d4017bbb8cc6055b0b711
package main import "strconv" /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param num int整型一维数组 * @return int整型二维数组 */ func threeSum(a []int) [][]int { // write code here ress := [][]int{} bubbleSort(a) n := len(a) isExist := map[string]bool{} for i := 0; i < n; i++ { for j := i + 1; j < n; j++ { for k := n - 1; k > j; k-- { if a[i]+a[j]+a[k] == 0 { key:=strconv.Itoa(a[i])+strconv.Itoa(a[j])+strconv.Itoa(a[k]) if !isExist[key] { res := []int{a[i], a[j], a[k]} ress = append(ress, res) isExist[key]=true } } } } } return ress } func bubbleSort(a []int) { n := len(a) for i := 0; i < n; i++ { for j := 0; j < n-i-1; j++ { if a[j] > a[j+1] { a[j], a[j+1] = a[j+1], a[j] } } } }