217. Contains Duplicate

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.

Constraints

Approach

Examples

Input: [1, 2, 3, 1]

Output: true

Solutions

/**
 * Time complexity : O(N^2)
 * Space complexity : O(1)
 */

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[j] == nums[i]) return true;  
            }
        }
        return false;
    }
}

Follow up

Last updated

Was this helpful?