Skip to content

Instantly share code, notes, and snippets.

@heyodai
Created September 22, 2021 00:11
Show Gist options
  • Save heyodai/68a44e1e27424d0fcbfd93cc94230385 to your computer and use it in GitHub Desktop.
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.
/**
* 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