Contains Duplicates I


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.


Solution 1. Brute Force [Time Limit Exceeded]

Two for loops, compare the items from two loops, and return the result.

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

Solution 2. Sort and Compare

If the array is sorted, then the same elements must lay next to each other.

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

Solution 3. Set

Kind of like in Python...

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

results matching ""

    No results matching ""