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

Contains Duplicate

时间:2016-05-18 12:41:20      阅读:150      评论: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.

分析:查找数组元素是否有重复。若一个一个比较,时间复杂度达到O(n2),所以以空间换时间,用一个集合记录之前遇到过的数字,如果新的数字已经在集合中出现过了,则说明有重复。

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

 

Contains Duplicate

标签:

原文地址:http://www.cnblogs.com/zywu/p/5504485.html

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