Skip to content

Commit 978ccb1

Browse files
committed
Added July 23 Challenge
1 parent 24e45fd commit 978ccb1

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
package com.leetcode.scala.monthly2020.july
2+
3+
import scala.collection.mutable
4+
5+
6+
/*
7+
* Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly
8+
* twice. Find the two elements that appear only once.
9+
*
10+
* */
11+
12+
/*
13+
* Input: [1,2,1,3,2,5]
14+
Output: [3,5]
15+
*
16+
* Note:
17+
1. The order of the result is not important. So in the above example, [5, 3] is also correct.
18+
2. Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity.
19+
*
20+
* */
21+
22+
/*
23+
* Approach: Bit Manipulation
24+
*
25+
* */
26+
27+
object SingleNumberIII {
28+
def main(args: Array[String]): Unit = {
29+
val nums = Array(1, 2, 1, 3, 2, 5)
30+
val result = singleNumber(nums)
31+
println(s"Result: ${result.mkString(" ")}, ${result.mkString(" ") == "5 3"}")
32+
}
33+
34+
//Without Extra Space
35+
def singleNumber(nums: Array[Int]): Array[Int] = {
36+
var num1: Int = 0
37+
for (num <- nums) {
38+
num1 ^= num
39+
}
40+
num1 &= -num1
41+
var result = Array.fill[Int](2)(0)
42+
for (num <- nums) {
43+
if ((num1 & num) == 0) {
44+
result(0) ^= num
45+
} else {
46+
result(1) ^= num
47+
}
48+
}
49+
result
50+
}
51+
52+
53+
// Using Extra Space
54+
// Time Complexity - O(n)
55+
// Space Complexity - O(n)
56+
57+
def singleNumberES(nums: Array[Int]): Array[Int] = {
58+
val set: mutable.HashSet[Int] = mutable.HashSet()
59+
for (num <- nums) {
60+
if (set.contains(num)) {
61+
set.remove(num)
62+
} else {
63+
set.add(num)
64+
}
65+
}
66+
set.toArray
67+
}
68+
}

0 commit comments

Comments
 (0)