Skip to content

Commit 85d11de

Browse files
committed
add FindAllDuplicatesInAnArray - Day 6
1 parent 47cb823 commit 85d11de

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package com.concept.scala.leetcode_30days_challenge_August2020
2+
3+
/** *
4+
* Day 6
5+
*
6+
* @todo Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
7+
* Find all the elements that appear twice in this array.
8+
* Could you do it without extra space and in O(n) runtime?
9+
* @example Example:
10+
* Input:
11+
* [4,3,2,7,8,2,3,1]
12+
*
13+
* Output:
14+
* [2,3]
15+
* @see https://leetcode.com/problems/find-all-duplicates-in-an-array/
16+
* OR
17+
* https://leetcode.com/explore/challenge/card/august-leetcoding-challenge/549/week-1-august-1st-august-7th/3414/
18+
*/
19+
object FindAllDuplicatesInAnArray {
20+
def main(args: Array[String]): Unit = {
21+
println(findDuplicates(Array(4, 3, 2, 7, 8, 2, 3, 1)).mkString(","))
22+
}
23+
24+
def findDuplicates(nums: Array[Int]): List[Int] = nums diff nums.distinct toList
25+
26+
def findDuplicates2(nums: Array[Int]): List[Int] = nums.map(e => (e, nums.count(_ == e))).filter(_._2 == 2).map(_._1).distinct.toList
27+
28+
def findDuplicates3(nums: Array[Int]): List[Int] = {
29+
nums.groupBy(identity).collect {
30+
case (num, count) if count.lengthCompare(1) > 0 => num
31+
}.toList
32+
}
33+
34+
def findDuplicates4(nums: Array[Int]): List[Int] = {
35+
nums.foldLeft(Map[Int, Int]()) { (acc, n) =>
36+
val count = acc.get(n).fold(1)(_ + 1)
37+
acc + (n -> count)
38+
}.filter(_._2 == 2).keys.toList
39+
}
40+
41+
def findDuplicates5(nums: Array[Int]): List[Int] = {
42+
nums.indices.foreach(index => {
43+
val indexToUpdate = nums(index) % (nums.length + 1) - 1
44+
nums(indexToUpdate) = nums(indexToUpdate) + (nums.length + 1)
45+
})
46+
nums.indices.filter(index => nums(index) > 2 * (nums.length + 1)).map(_ + 1).toList
47+
}
48+
49+
}
50+

0 commit comments

Comments
 (0)