[LeetCode] 217. Contains Duplicate

原题链接: https://leetcode.com/problems/contains-duplicate/

1. 题目介绍

给出一个一维数组,数组中的元素全都是整数,判断数组中是否有元素重复。

如果有元素重复了,返回 true,如果没有元素重复,那就返回 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

2. 解题思路

2.1 方法1 先排序再找重复

首先将数组排序,排序之后遍历数组。如果某个数和它前面的数是一样的,那就是重复了。
实现代码

class Solution {
    public boolean containsDuplicate(int[] nums) {
        int length = nums.length;
        if(length == 0) {
        	return false;
        }
        
        Arrays.sort(nums);
        for(int i = 1;i<length;i++) {
        	if(nums[i] == nums[i-1]) {
        		return true;
        	}
        }
        return false;
    }
}

2.2 方法2 借助Set

Set 是一种无序的集合。遍历数组,每遇到一个数,判断一下是否已经在set集合里面了,如果在的话,就是重复出现的,如果不在里面,那就是第一次出现,要把它放进set去。

实现代码

class Solution {
    public boolean containsDuplicate(int[] nums) {
        int length = nums.length;
        if(length == 0) {
        	return false;
        }
        
        Set<Integer> set = new HashSet<>(length);
        for(int i =0; i<length ; i++) {
        	if(set.contains(nums[i]) == true) {
        		return true;
        	}
        	set.add(nums[i]);
        }
        return false;
    }
}

3. 参考链接

https://leetcode.com/problems/contains-duplicate/solution/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值