首页 > 其他 > 详细

217. Contains Duplicate

时间:2015-11-23 00:41:53      阅读:306      评论:0      收藏:0      [点我收藏+]

题目:

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.

链接: http://leetcode.com/problems/contains-duplicate/

题解:

求数组中是否有重复元素。第一反应是用HashSet。 还可以用Bitmap来写。二刷要都补充上。

Time Complexity - O(n), Space Complexity - O(n)

public class Solution {
    public boolean containsDuplicate(int[] nums) {
        if(nums == null || nums.length == 0)
            return false;
        Set<Integer> set = new HashSet<>();
        
        for(int i : nums) {
            if(set.contains(i))
                return true;
            else
                set.add(i);
        }
        
        return false;
    }
}

 

Reference:

https://leetcode.com/discuss/70186/88%25-and-99%25-java-solutions-with-custom-hashing

https://leetcode.com/discuss/59208/20ms-c-use-bitmap

https://leetcode.com/discuss/37219/possible-solutions

https://leetcode.com/discuss/37190/java-o-n-ac-solutions-with-hashset-and-bitset

217. Contains Duplicate

原文:http://www.cnblogs.com/yrbbest/p/4987090.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!