[LeetCode]217. Contains Duplicate

本文解析了如何通过排序和哈希表两种方法解决Java编程中的ContainsDuplicate问题。首先介绍了使用排序算法将数组升序排列,通过比较相邻元素找出重复。另一种方法是利用HashSet的特性,遍历数组判断元素是否已存在于集合中。两种方法分别分析了时间复杂度和空间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

217. Contains Duplicate

一、题目

Problem Description:
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

二、题解

  • 一道简单题,如果数组里有重复的元素就返回true,否则返回false。

2.1 Approach #1 : Sorting

先对数组进行排序;后循环判断当前元素与后一个元素是否相等来验证有无重复元素。

Time complexity : O ( n l o g n ) O(nlogn) O(nlogn). 排序方法Arrays.sort()时间复杂度是 O ( n l o g n ) O(nlogn) O(nlogn);for循环的时间复杂度是 O ( n ) O(n) O(n)。时间复杂度为 m a x ( O ( l o g n ) , O ( n ) ) = O ( n l o g n ) max(O(logn), O(n))=O(nlogn) max(O(logn),O(n))=O(nlogn)
Space complexity : O ( 1 ) O(1) O(1).

//Sorting
//Time complexity : O(nlogn); Space complexity : O(1)
class Solution {
    public boolean containsDuplicate(int[] nums) {
        Arrays.sort(nums); // 升序排序
        for(int i = 0; i < nums.length - 1; i++){
            if(nums[i] == nums[i+1]){
                return true;
            }
        }
        return false;
    }
}

2.2 Approach #2 : Hash Table

遍历nums数组中的所有元素。如果当前元素在HashSett中不存在,则将其加入HashSet;若存在,则直接返回true即可。

下面以HashSet集合为例,HashMap同理。

Time complexity : O ( n ) O(n) O(n). 理想情况下,HashSet的增、删、改、查等操作的时间复杂度都为 O ( 1 ) O(1) O(1)
Space complexity : O ( n ) O(n) O(n)

//Hash Table
//Time complexity : O(n); Space complexity : O(n)
class Solution {
    public boolean containsDuplicate(int[] nums) {
        Set<Integer> set = new HashSet<>();
        for(int x : nums){
            if(set.contains(x)) return true;
            else set.add(x);
        }
        return false;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值