354.russian-doll-envelopes.go 872 B

1234567891011121314151617181920212223242526272829303132333435
  1. type nx2arr [][]int
  2. func (arr nx2arr) Len() int { return len(arr) }
  3. func (arr nx2arr) Less(i, j int) bool {
  4. if arr[i][0] != arr[j][0] {
  5. return arr[i][0] < arr[j][0]
  6. } else {
  7. return arr[j][1] < arr[i][1] // If the width is the same, the tallest is in front
  8. }
  9. }
  10. func (arr nx2arr) Swap(i, j int) { arr[i], arr[j] = arr[j], arr[i] }
  11. func maxEnvelopes(envelopes [][]int) (n int) { // Just like "the longest increasing substring"
  12. sort.Sort(nx2arr(envelopes))
  13. queue := make([][]int, 0)
  14. for i := range envelopes {
  15. beg, end := 0, n-1
  16. for beg <= end {
  17. mid := beg + (end-beg)/2
  18. if queue[mid][1] < envelopes[i][1] { // Binary search with duplicates
  19. beg = mid + 1
  20. } else if envelopes[i][1] <= queue[mid][1] {
  21. end = mid - 1
  22. }
  23. }
  24. if beg == n {
  25. queue = append(queue, envelopes[i])
  26. n++
  27. } else {
  28. queue[beg] = envelopes[i]
  29. }
  30. }
  31. return
  32. }