|
| 1 | +package Solution |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "testing" |
| 6 | +) |
| 7 | + |
| 8 | +func IsEqualForSlice(a, b []int) bool { |
| 9 | + if len(a) != len(b) { |
| 10 | + fmt.Println("a") |
| 11 | + return false |
| 12 | + } |
| 13 | + // 为了和reflect.DeepEqual的结果保持一致: |
| 14 | + // []int{} != []int(nil) |
| 15 | + if (a == nil) != (b == nil) { |
| 16 | + fmt.Println("a") |
| 17 | + |
| 18 | + return false |
| 19 | + } |
| 20 | + |
| 21 | + // 此处的处的bounds check能够明确保证v != b[i]中的b[i] |
| 22 | + // 会出现越界错误,从而避免了b[i]中的越界检查从而提高效率 |
| 23 | + // https://go101.org/article/bounds-check-elimination.html |
| 24 | + b = b[:len(a)] |
| 25 | + |
| 26 | + // 循环检测每个元素是否相等 |
| 27 | + for i, v := range a { |
| 28 | + if v != a[i] { |
| 29 | + return false |
| 30 | + } |
| 31 | + } |
| 32 | + return true |
| 33 | +} |
| 34 | + |
| 35 | +func TestTwoSum(t *testing.T) { |
| 36 | + |
| 37 | + t.Run("Test-1", func(t *testing.T) { |
| 38 | + data := []int{3, 2, 4} |
| 39 | + target := 6 |
| 40 | + want := []int{1, 2} |
| 41 | + |
| 42 | + got := twoSum(data, target) |
| 43 | + if !IsEqualForSlice(got, want) { |
| 44 | + t.Error("GOT:", got, " WANT:", want) |
| 45 | + } |
| 46 | + }) |
| 47 | + |
| 48 | + t.Run("Test-2", func(t *testing.T) { |
| 49 | + data := []int{2, 7, 11, 15} |
| 50 | + target := 9 |
| 51 | + want := []int{0, 1} |
| 52 | + |
| 53 | + got := twoSum(data, target) |
| 54 | + if !IsEqualForSlice(got, want) { |
| 55 | + t.Error("GOT:", got, " WANT:", want) |
| 56 | + } |
| 57 | + }) |
| 58 | + |
| 59 | + t.Run("Test-3", func(t *testing.T) { |
| 60 | + data := []int{7, 6, 5, 3, 2, 1, 4, 9, 10} |
| 61 | + target := 17 |
| 62 | + want := []int{0, 8} |
| 63 | + |
| 64 | + got := twoSum(data, target) |
| 65 | + if !IsEqualForSlice(got, want) { |
| 66 | + t.Error("GOT:", got, " WANT:", want) |
| 67 | + } |
| 68 | + }) |
| 69 | + |
| 70 | +} |
| 71 | + |
| 72 | +func TestTwoSum1(t *testing.T) { |
| 73 | + data := []int{7, 6, 5, 3, 2, 1, 4, 9, 10} |
| 74 | + target := 17 |
| 75 | + fmt.Println(twoSum1(data, target)) |
| 76 | +} |
0 commit comments