码迷,mamicode.com
首页 > 其他好文 > 详细

Contains Duplicate LT217

时间:2019-05-12 10:39:59      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:nta   compare   idea   solution   scan   div   ica   ORC   inpu   

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

标签:nta   compare   idea   solution   scan   div   ica   ORC   inpu   

原文地址:https://www.cnblogs.com/taste-it-own-it-love-it/p/10850981.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!