Contains Duplicate LT217
Posted taste-it-own-it-love-it
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Contains Duplicate LT217相关的知识,希望对你有一定的参考价值。
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.
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 }
以上是关于Contains Duplicate LT217的主要内容,如果未能解决你的问题,请参考以下文章
217 Contains Duplicate (Array)
leetcode 217. Contains Duplicate
LeetCode 217. Contains Duplicate