Contains Duplicate

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

public class Solution {
    public boolean containsDuplicate(int[] nums) {
        if(nums.length<=1) return false;
        Arrays.sort(nums);
        for(int i=0;i<nums.length-1;i++) {
            if(nums[i]==nums[i+1]) return true;
        }
        return false;
    }
}

解法二:用HashSet,最坏时间复杂度O(n).

public class Solution {
    public boolean containsDuplicate(int[] nums) {
        HashSet<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;
    }
}

 

posted @ 2015-05-25 12:40  mrpod2g  阅读(721)  评论(0编辑  收藏  举报