Contains Duplicate

Given an array of integers, find if the array contains any duplicates.

Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.

Example 1:

Input: [1,2,3,1]
Output: true

Example 2:

Input: [1,2,3,4]
Output: false

Example 3:

Input: [1,1,1,3,3,4,3,2,4,2]
Output: true

My idea was pretty simple: Firstly, sort the array. And then loop through the array, if there are two consecutive elements the same, store the duplicated one in the empty array. Return whether the duplicate array is 0 or not.

Remember the loop starts from the index 1 as I am comparing the next index with the previous one, whose the smallest index is 0.

Python Solution:

# pythonclass Solution(object):
def containsDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: bool

"""
dup = 0
nums.sort()

for i in range(1, len(nums)):
if nums[i] == nums[i - 1]:
dup += 1
return dup != 0

JavaScript Solution:

/**
* @param {number[]} nums
* @return {boolean}
*/
var containsDuplicate = function(nums) {

dup = 0;

nums.sort();

for (i = 1; i < nums.length; i++){
if (nums[i] == nums[i - 1]){
dup ++;
}

}

return dup != 0;

};

Link

Special Thanks to Programmer Mitch, I learned a lot from his videos.

--

--

--

My homepage to record my thought processes for solving SQL and Algorithm questions

Recommended from Medium

Object Recognition using CNN model

How to find secrets in websites

A Complete Guide To props.children In React

How JavaScript Grew Up and Became a Real Language

Embed a YouTube Video Player using YouTube Iframe API and JavaScript

YouTube Iframe API

Use your Cerebral

Test Post

Angular 2 for Java Projects

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Jen-Li Chen

Jen-Li Chen

In love with telling stories with data

More from Medium

Leetcode — 50. Pow(x, n) (Medium)

Identify Complete Binary Tree — Leetcode 958

Queue | The Data Structure which Schedules the Disk

55. Jump Game