Created
July 12, 2017 20:12
-
-
Save krishnanraman/4b1ba7606d5c8ef0399ffb0ad45a1363 to your computer and use it in GitHub Desktop.
stitchfix coding exercise
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| Given an unsorted array/list of integers, write a function that: | |
| - returns True iff there are duplicate integers in the list | |
| - returns False otherwise | |
| [-12, 32, 56, -2] -> False | |
| [32, 23, 23, 1, 5 ] -> True | |
| */ | |
| // To execute Scala code, please define an object named Solution that extends App | |
| object Solution extends App { | |
| val a = List(-12, 32, 56, -2) | |
| val b = List(32, 23, 23, 1, 5) | |
| println(dupes(a)) | |
| println(dupes(b)) | |
| println(dupes2(a.toArray)) | |
| println(dupes2(b.toArray)) | |
| def dupes(x:List[Int]):Boolean = { | |
| x.distinct.size != x.size | |
| } // O(n) | |
| def dupes2(x:Array[Int]):Boolean = { | |
| val sorted = x.sorted | |
| var prev = -1 | |
| var curr = -1 | |
| var done = false | |
| (0 until sorted.size).foreach { i=> | |
| curr = sorted(i) | |
| if (!done) { | |
| if (prev != curr) { | |
| prev = curr | |
| } else { | |
| done = true | |
| } | |
| } | |
| } | |
| done | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment