217. Contains Duplicate(Solution || Leetcode easy || Java)

Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.

Example 1:

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

Example 2:

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

Example 3:

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

Constraints:

  • -109 <= nums[i] <= 109

SOLUTION:

class Solution {
public boolean containsDuplicate(int[] nums) {
//first we’ll sort our array
Arrays.sort(nums);

//if any number after sorting is equal to number after it, it means that number has a duplicate, hence, we return true
for(int k = 0; k < nums.length — 1; k++){
if(nums[k] == nums[k+1]){
return true;
}
}
//if you don’t find any duplicate, return false
return false;
}
}

Thank you for reading. If you have any queries then, please let me know in the comment section. I will surely be responsive toward it.

--

--

Solutions to all your coding related problems at one point. DSA question on daily basis and much more.

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
Palakkgoyal

Solutions to all your coding related problems at one point. DSA question on daily basis and much more.