Contains Duplicate LT217

Given an array of integers, find if the array contains any duplicates.app

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.ide

Example 1:idea

Input: [1,2,3,1]
Output: true

Example 2:spa

Input: [1,2,3,4]
Output: false

Example 3:code

Input: [1,1,1,3,3,4,3,2,4,2]
Output: true

Idea 1. HashMap(Set)blog

Time complexity: O(N)element

Space complexity: O(N)it

other ideas: bruteforce(for each element, scan the whole to see if there is the same value element), sort(compare each element with its neighbour).io

 1 class Solution {
 2     public boolean containsDuplicate(int[] nums) {
 3        Set<Integer> cache = new HashSet<>();
 4         
 5         for(int num: nums) {
 6             if(cache.contains(num)) {
 7                 return true;
 8             }
 9             cache.add(num);
10         }
11         
12         return false;
13     }
14 }
相關文章
相關標籤/搜索