Skip to content

Commit 572c608

Browse files
add 2161 alt sol
1 parent e94f0ad commit 572c608

File tree

3 files changed

+58
-5
lines changed

3 files changed

+58
-5
lines changed

contest/src/main/java/com/github/contest/Execute.kt

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
package com.github.contest
22

33

4-
import com.github.contest.dp.longestArithSeqLength
4+
import com.github.contest.array.pivotArrayAlternativeSolution
55
import java.util.TreeMap
66

77

@@ -11,7 +11,7 @@ import java.util.TreeMap
1111

1212
fun main() {
1313

14-
longestArithSeqLength(intArrayOf(3, 6, 9, 12))
14+
pivotArrayAlternativeSolution(intArrayOf(9, 12, 5, 10, 14, 3, 10), 10)
1515
}
1616

1717
fun generateTesting() {

contest/src/main/java/com/github/contest/array/AlternativeSolutionArray.kt

Lines changed: 54 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -73,10 +73,12 @@ fun applyOperationsAlternativeSolution(nums: IntArray): IntArray {
7373

7474
/**
7575
* 2570. Merge Two 2D Arrays by Summing Values
76-
* AlternativeSolution
76+
* Alternative Solution
7777
*/
7878

79-
fun mergeArraysAlternativeSolution(nums1: Array<IntArray>, nums2: Array<IntArray>): Array<IntArray> {
79+
fun mergeArraysAlternativeSolution(
80+
nums1: Array<IntArray>, nums2: Array<IntArray>
81+
): Array<IntArray> {
8082
val result = mutableListOf<IntArray>()
8183
var i = 0
8284
var j = 0
@@ -112,4 +114,53 @@ fun mergeArraysAlternativeSolution(nums1: Array<IntArray>, nums2: Array<IntArray
112114
}
113115

114116
return result.toTypedArray()
115-
}
117+
}
118+
119+
/**
120+
* 2161. Partition Array According to Given Pivot
121+
* Alternative Solution
122+
*/
123+
124+
125+
fun pivotArrayAlternativeSolution(nums: IntArray, pivot: Int): IntArray {
126+
val n = nums.size
127+
val result = IntArray(n)
128+
var lessIndex = 0
129+
var greaterIndex = n - 1
130+
var equalCount = 0
131+
132+
for (num in nums) {
133+
when {
134+
num < pivot -> {
135+
result[lessIndex] = num
136+
lessIndex++
137+
}
138+
139+
num > pivot -> {
140+
result[greaterIndex] = num
141+
greaterIndex--
142+
}
143+
144+
else -> equalCount++
145+
}
146+
}
147+
148+
while (equalCount > 0) {
149+
result[lessIndex] = pivot
150+
lessIndex++
151+
equalCount--
152+
}
153+
154+
//Reverse the greater part
155+
var start = lessIndex
156+
var end = n - 1
157+
while (start < end) {
158+
val temp = result[start]
159+
result[start] = result[end]
160+
result[end] = temp
161+
start++
162+
end--
163+
}
164+
165+
return result
166+
}

contest/src/main/java/com/github/contest/array/ArrayLeetcode.kt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,3 +143,5 @@ fun mergeArrays(nums1: Array<IntArray>, nums2: Array<IntArray>): Array<IntArray>
143143

144144

145145

146+
147+

0 commit comments

Comments
 (0)