# Java solution leetcode 217. There are duplicate elements

2021-08-23 08:04:45

Given an array of integers , Determine whether there are duplicate elements .
If a value exists, it appears at least twice in the array , The function returns true . If every element in the array is different , Then return to false .

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

• Solve by sorting
class Solution {
public boolean containsDuplicate(int[] nums) {
// solution1:  Sort
//  Time complexity ：O(NlogN), among  N  Is the length of the array . Array needs to be sorted .
//  Spatial complexity ：O(logN)
Arrays.sort(nums);
for(int i=0; i < nums.length - 1; i++){
if(nums[i] == nums[i+1]){
return true;
}
}
return false;
}
}

• 1.
• 2.
• 3.
• 4.
• 5.
• 6.
• 7.
• 8.
• 9.
• 10.
• 11.
• 12.
• 13.
• 14.

• Solve through hash table
class Solution {
public boolean containsDuplicate(int[] nums) {
// solution2:  Hashtable
//  Time complexity ：O(N)
//  Spatial complexity ：O(N), among  NN  Is the length of the array .
Set<Integer> set = new HashSet<Integer>();
for(int x : nums){
return true;
}
}
return false;
}
}

• 1.
• 2.
• 3.
• 4.
• 5.
• 6.
• 7.
• 8.
• 9.
• 10.
• 11.
• 12.
• 13.
• 14.