Skip to content

Commit 220150c

Browse files
authored
feat: add go solution to lc problem: No.0315 (doocs#847)
No.0315.Count of Smaller Numbers After Self
1 parent 6fd57b6 commit 220150c

File tree

1 file changed

+63
-0
lines changed
  • solution/0300-0399/0315.Count of Smaller Numbers After Self

1 file changed

+63
-0
lines changed

solution/0300-0399/0315.Count of Smaller Numbers After Self/README.md

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,8 @@
7373
- 线段树的每个叶子节点代表一个长度为 1 的元区间 `[x, x]`
7474
- 对于每个内部节点 `[l, r]`,它的左儿子是 `[l, mid]`,右儿子是 `[mid + 1, r]`, 其中 `mid = ⌊(l + r) / 2⌋` (即向下取整)。
7575

76+
**方法三:归并排序**
77+
7678
<!-- tabs:start -->
7779

7880
### **Python3**
@@ -523,6 +525,67 @@ func countSmaller(nums []int) []int {
523525
}
524526
```
525527

528+
归并排序:
529+
530+
```go
531+
type Pair struct {
532+
val int
533+
index int
534+
}
535+
536+
var (
537+
tmp []Pair
538+
count []int
539+
)
540+
541+
func countSmaller(nums []int) []int {
542+
tmp, count = make([]Pair, len(nums)), make([]int, len(nums))
543+
array := make([]Pair, len(nums))
544+
for i, v := range nums {
545+
array[i] = Pair{val: v, index: i}
546+
}
547+
sorted(array, 0, len(array)-1)
548+
return count
549+
}
550+
551+
func sorted(arr []Pair, low, high int) {
552+
if low >= high {
553+
return
554+
}
555+
mid := low + (high-low)/2
556+
sorted(arr, low, mid)
557+
sorted(arr, mid+1, high)
558+
merge(arr, low, mid, high)
559+
}
560+
561+
func merge(arr []Pair, low, mid, high int) {
562+
left, right := low, mid+1
563+
idx := low
564+
for left <= mid && right <= high {
565+
if arr[left].val <= arr[right].val {
566+
count[arr[left].index] += right - mid - 1
567+
tmp[idx], left = arr[left], left+1
568+
} else {
569+
tmp[idx], right = arr[right], right+1
570+
}
571+
idx++
572+
}
573+
for left <= mid {
574+
count[arr[left].index] += right - mid - 1
575+
tmp[idx] = arr[left]
576+
idx, left = idx+1, left+1
577+
}
578+
for right <= high {
579+
tmp[idx] = arr[right]
580+
idx, right = idx+1, right+1
581+
}
582+
// 排序
583+
for i := low; i <= high; i++ {
584+
arr[i] = tmp[i]
585+
}
586+
}
587+
```
588+
526589
### **...**
527590

528591
```

0 commit comments

Comments
 (0)