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.

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

Example 1:

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

Example 2:

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

Example 3:

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

Idea 1. HashMap(Set)

Time complexity: O(N)

Space complexity: O(N)

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

 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 }
扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄