Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit efd07b1

Browse filesBrowse files
author
night
committed
pramp issue
1 parent a90b71d commit efd07b1
Copy full SHA for efd07b1

File tree

Expand file treeCollapse file tree

1 file changed

+48
-0
lines changed
Filter options
Expand file treeCollapse file tree

1 file changed

+48
-0
lines changed
+48Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package com.blankj.pramp
2+
3+
import com.blankj.ext.print
4+
import java.util.*
5+
import kotlin.math.min
6+
7+
class SortKMessArray {
8+
fun sortKMessedArray(arr: IntArray, k: Int): IntArray {
9+
val n = arr.size
10+
for (i in 0 until n) {
11+
var minIndex = i
12+
for (j in i + 1 until min(i + k + 1, n)) {
13+
if (arr[j] < arr[minIndex]) {
14+
minIndex = j
15+
}
16+
}
17+
if (minIndex != i) {
18+
val temp = arr[minIndex]
19+
arr[minIndex] = arr[i]
20+
arr[i] = temp
21+
}
22+
}
23+
return arr
24+
}
25+
26+
fun sortKMessedArrayWithHeap(arr: IntArray, k: Int): IntArray {
27+
if (arr.isEmpty()) return arr
28+
val heap = PriorityQueue<Int>()
29+
val minCount = k + 1
30+
for (i in 0..<min(minCount, arr.size)) {
31+
heap.add(arr[i])
32+
}
33+
var index = 0
34+
for (i in minCount..<arr.size) {
35+
arr[index++] = heap.remove()
36+
heap.add(arr[i])
37+
}
38+
val iterator = heap.iterator()
39+
while (iterator.hasNext()) {
40+
arr[index++] = heap.remove()
41+
}
42+
return arr
43+
}
44+
}
45+
46+
fun main() {
47+
SortKMessArray().sortKMessedArrayWithHeap(intArrayOf(1, 4, 5, 2, 3, 7, 8, 6, 10, 9), 2).print()
48+
}

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.