github.com/qiuhoude/go-web@v0.0.0-20220223060959-ab545e78f20d/algorithm/leetcode/minimum-number-of-arrows-to-burst-balloons_test.go (about)

     1  package leetcode
     2  
     3  import (
     4  	"fmt"
     5  	"sort"
     6  	"testing"
     7  )
     8  
     9  //452. 用最少数量的箭引爆气球 https://leetcode-cn.com/problems/minimum-number-of-arrows-to-burst-balloons/
    10  
    11  func findMinArrowShots(points [][]int) int {
    12  	n := len(points)
    13  	if n == 0 {
    14  		return 0
    15  	}
    16  	sort.Slice(points, func(i, j int) bool { // 结束位置升序
    17  		if points[i][1] < points[j][1] {
    18  			return true
    19  		} else {
    20  			if points[i][1] == points[j][1] {
    21  				return points[i][0] < points[j][0]
    22  			}
    23  			return false
    24  		}
    25  	})
    26  	//fmt.Printf("%v\n", points)
    27  	ret := 1
    28  	latestEnd := points[0][1]
    29  	for i := 1; i < n; i++ {
    30  		if points[i][0] > latestEnd {
    31  			ret++
    32  			latestEnd = points[i][1]
    33  		}
    34  	}
    35  	return ret
    36  }
    37  
    38  func TestFFindMinArrowShots(t *testing.T) {
    39  	tests := []struct {
    40  		arg  [][]int
    41  		want int
    42  	}{
    43  		{[][]int{{10, 16}, {2, 8}, {1, 6}, {7, 12}}, 2},
    44  		{[][]int{{10, 16}, {2, 8}, {1, 6}, {7, 12}, {13, 15}, {4, 12}}, 3},
    45  	}
    46  
    47  	for _, tt := range tests {
    48  		name := fmt.Sprintf("%v", tt.arg)
    49  		t.Run(name, func(t *testing.T) {
    50  			if got := findMinArrowShots(tt.arg); got != tt.want {
    51  				t.Errorf("findMinArrowShots() => want:%v but got:%v", tt.want, got)
    52  			}
    53  		})
    54  	}
    55  
    56  }