Created
September 22, 2021 00:11
-
-
Save heyodai/68a44e1e27424d0fcbfd93cc94230385 to your computer and use it in GitHub Desktop.
Check an int array for duplicate values. Written for leetcode.com challenge #217.
This file contains 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
/** | |
* Check an int array for duplicate values. | |
* Written for leetcode.com challenge #217. | |
* | |
* @param {int[]} nums Array of int values to check. | |
* @return {boolean} TRUE if duplicate values found, FALSE if every element is distinct. | |
* | |
* @see https://leetcode.com/problems/contains-duplicate/ | |
*/ | |
var containsDuplicate = function(nums) { | |
/** | |
* forEach does not allow us to return a value in JavaScript, | |
* so the use of a bool value (result) is necessary. | |
* | |
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach | |
*/ | |
let result = false; | |
let scanned_values = []; | |
nums.forEach( | |
function(element) { | |
if (scanned_values.indexOf(element) == -1) { // indicates no match found | |
scanned_values.push(element); | |
} | |
else { // a match was found | |
result = true; | |
} | |
} | |
); | |
return result; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment