Leetcode LeetCode algorithm punch card learning day 3

4. There are duplicate elements

Given an integer array, determine whether there are duplicate elements.
If there is a value that appears at least twice in the array, the function returns true. If every element in the array is different, false is returned.

Method 1: Mine, but beyond the time limit

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

Method 2: Mine, after sorting first, compare adjacent ones

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

Method 3: Official Answer-Hash Table

class Solution {
    
    
    public boolean containsDuplicate(int[] nums) {
    
    
        Set<Integer> set = new HashSet<Integer>();
        for (int x : nums) {
    
    
            if (!set.add(x)) {
    
    
                return true;
            }
        }
        return false;
    }
}

作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/contains-duplicate/solution/cun-zai-zhong-fu-yuan-su-by-leetcode-sol-iedd/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

Guess you like

Origin blog.csdn.net/Shadownow/article/details/112803025