Skip to content

Commit f5d3e1e

Browse files
add 3396
1 parent 966ff98 commit f5d3e1e

File tree

2 files changed

+43
-2
lines changed

2 files changed

+43
-2
lines changed

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

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
package com.github.contest
22

33

4-
import com.github.contest.strings.freqAlphabets
4+
import com.github.contest.hashTable.minimumOperations
55
import java.util.TreeMap
66

77

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

1212
fun main() {
1313

14-
freqAlphabets("12345678910#11#12#13#14#15#16#17#18#19#20#21#22#23#24#25#26#").also { println(it) }
14+
minimumOperations(intArrayOf(1, 2, 3, 4, 2, 3, 3, 5, 7)).also { println(it) }
1515
}
1616

1717
fun testing() {

contest/src/main/java/com/github/contest/hashTable/HashTableLeetcode.kt

+41
Original file line numberDiff line numberDiff line change
@@ -271,4 +271,45 @@ fun repeatedCharacter(s: String): Char {
271271
}
272272

273273
return 'a'
274+
}
275+
276+
/**
277+
* 3396. Minimum Number of Operations to Make Elements in Array Distinct
278+
*/
279+
280+
fun minimumOperations(nums: IntArray): Int {
281+
val map = mutableMapOf<Int, Int>()
282+
var operations = 0
283+
284+
for (num in nums) map[num] = map.getOrDefault(num, 0) + 1
285+
286+
if (map.size == nums.size) return 0
287+
288+
for (i in nums.indices step 3) {
289+
if (i + 2 < nums.size) {
290+
val one = nums[i]
291+
val two = nums[i + 1]
292+
val three = nums[i + 2]
293+
map.reduceOrRemove(one)
294+
map.reduceOrRemove(two)
295+
map.reduceOrRemove(three)
296+
var isUnique = true
297+
for (value in map.values) {
298+
if (value > 1) {
299+
isUnique = false
300+
break
301+
}
302+
}
303+
if (isUnique) return operations + 1
304+
operations++
305+
}
306+
}
307+
308+
return if (map.size > 0) operations + 1 else operations
309+
310+
}
311+
312+
private fun MutableMap<Int, Int>.reduceOrRemove(key: Int) {
313+
this[key] = this.getOrDefault(key, 0) - 1
314+
if (this.getOrDefault(key, 0) == 0) this.remove(key)
274315
}

0 commit comments

Comments
 (0)