-
Notifications
You must be signed in to change notification settings - Fork 43
/
removeDuplicates.scala
59 lines (53 loc) · 1.47 KB
/
removeDuplicates.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// V0 : to fix
// object Solution {
// def removeDuplicates(nums: Array[Int]): Int = {
// if (nums.length == 0) { 0 }
// else {
// var j = 0
// for (i <- nums.indices){
// if (nums(i) != nums(j)) {
// {nums(i) = nums(j+1)
// nums(j+1) = nums(i)
// j = j + 1}
// }
// } j + 1
// }
// }
// }
// V1
// https://leetcode.com/problems/remove-duplicates-from-sorted-array/discuss/337877/scala-solution
object Solution {
def removeDuplicates(nums: Array[Int]): Int = {
def aux(s: Int, f: Int): Int = {
// 1-base and 0-base
if (f > nums.length - 1) s
else if (nums(s) == nums(f)) aux(s, f + 1)
else {
nums(s + 1) = nums(f)
aux(s + 1, f + 1)
}
}
if (nums.isEmpty) 0
else 1 + aux(0, 1)
}
}
// V1'
// https://leetcode.com/problems/remove-duplicates-from-sorted-array/discuss/351346/Scala-solution-using-foldLeft
object Solution {
def removeDuplicates(nums: Array[Int]): Int = {
if (nums.isEmpty) 0
else {
nums
.drop(1)
.foldLeft((1, nums(0)))((tuple, current) => {
val (uniqueCount: Int, previous: Int) = tuple
if (current == previous) (uniqueCount, current)
else {
nums(uniqueCount) = current
(uniqueCount + 1, current)
}
})
._1
}
}
}