其他分享
首页 > 其他分享> > LeetCode 0217 Contains Duplicate

LeetCode 0217 Contains Duplicate

作者:互联网

原题传送门

1. 题目描述

2. Solution 1

1、思路分析
Approach #1 (Naive Linear Search) [Time Limit Exceeded]

2、代码实现

package Q0299.Q0217ContainsDuplicate;

public class Solution1 {
    // Approach #1 (Naive Linear Search) [Time Limit Exceeded]
    public boolean containsDuplicate(int[] nums) {
        for (int i = 0; i < nums.length; i++)
            for (int j = 0; j < i; j++)
                if (nums[j] == nums[i]) return true;
        return false;
    }
}

3、复杂度分析
时间复杂度: O(n^2)
空间复杂度: O(1)

3. Solution 2

1、思路分析
Approach #2 (Sorting) [Accepted]

2、代码实现

package Q0299.Q0217ContainsDuplicate;

import java.util.Arrays;

public class Solution2 {
    // Approach #2 (Sorting) [Accepted]
    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;
    }
}

3、复杂度分析
时间复杂度: O(n log n)
空间复杂度: O(log n)

4. Solution 3

1、思路分析
Approach #3 (Set) [Accepted]

2、代码实现

package Q0299.Q0217ContainsDuplicate;

import java.util.HashSet;
import java.util.Set;

// Approach #3 (Set) [Accepted]
public class Solution3 {
    public boolean containsDuplicate(int[] nums) {
        Set<Integer> set = new HashSet<>();
        for (int x : nums) {
            if (set.contains(x)) return true;
            set.add(x);
        }
        return false;
    }
}

3、复杂度分析
时间复杂度: O(n)
空间复杂度: O(n)

标签:return,nums,int,复杂度,Contains,public,Duplicate,Approach,LeetCode
来源: https://www.cnblogs.com/junstat/p/16350626.html