0
点赞
收藏
分享

微信扫一扫

Java解 leetcode 217. 存在重复元素


题目:217. 存在重复元素


给定一个整数数组,判断是否存在重复元素。
如果存在一值在数组中出现至少两次,函数返回 true 。如果数组中每个元素都不相同,则返回 false 。



示例 1:
输入: [1,2,3,1]
输出: true

示例 2:
输入: [1,2,3,4]
输出: false

示例 3:
输入: [1,1,1,3,3,4,3,2,4,2]
输出: true


  • 通过排序解决
class Solution {
public boolean containsDuplicate(int[] nums) {
// solution1: 排序
// 时间复杂度:O(NlogN),其中 N 为数组的长度。需要对数组进行排序。
// 空间复杂度:O(logN)
Arrays.sort(nums);
for(int i=0; i < nums.length - 1; i++){
if(nums[i] == nums[i+1]){
return true;
}
}
return false;
}
}
  • 通过哈希表解决
class Solution {
public boolean containsDuplicate(int[] nums) {
// solution2: 哈希表
// 时间复杂度:O(N)
// 空间复杂度:O(N),其中 NN 为数组的长度。
Set<Integer> set = new HashSet<Integer>();
for(int x : nums){
if(!set.add(x)){
return true;
}
}
return false;
}
}



举报

相关推荐

0 条评论