Contains Duplicate Cont…
1 min readMay 9, 2019
Question: 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
You may view the full question here.
Approach 2: Let’s try a solution without using a map. First sort the array. This way, if there are any duplicates, they will appear consecutively in the array.
//Approach 2:
//Runtime: 3ms
//Memory usage: 43.7MBclass Solution {
public boolean containsDuplicate(int[] nums) {
return arrayApproach(nums);
}
private boolean arrayApproach(int[] nums){
Arrays.sort(nums);
for(int i = 1; i<nums.length; i++){
if(nums[i-1]==nums[i]){
return true;
}
}
return false;
}
}
Find more posts here.
Cheers & Chao!