Array:Contains Duplicate

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.

求数组中是否有重复元素问题。

1.最容易想到的解法就是将每个元素和数组中的所有元素一一比较,时间复杂度O(N^2),空间复杂度O(1)的解法:

public boolean containsDuplicate(int[] nums) {

        for(int i = 0; i < nums.length; i++) {
            for(int j = i + 1; j < nums.length; j++) {
                if(nums[i] == nums[j]) {
                    return true;
                }
            }
        }
        return false;
    }

2.时间复杂度改进的解法,先用sort将数组排序,然后将排序后的数组中每个元素与前一元素比较,时间复杂度O(N lgN),空间复杂度O(N):

 public boolean containsDuplicate(int[] nums) {

        Arrays.sort(nums);
        for(int ind = 1; ind < nums.length; ind++) {
            if(nums[ind] == nums[ind - 1]) {
                return true;
            }
        }
        return false;
    }

3.使用Set遍历数组并比较,时间复杂度O(N),空间复杂度O(N):

public boolean containsDuplicate(int[] nums) {

    final Set<Integer> distinct = new HashSet<Integer>();
    for(int num : nums) {
        if(distinct.contains(num)) {
            return true;
        }
        distinct.add(num);
    }
    return false;
}

 

Contains Duplicate II

Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k.

判断数组中是否存在坐标差不超过k的重复值

思路解析:

使用Set设置一个大小为k的滑动窗口,只存储数组中的k个元素,超过k时就将k前面的元素移除,通过set.add饭否发判断是否重复。

public class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        Set<Integer> set = new HashSet<>();
        for (int i = 0; i < nums.length; i++) {
            if (i > k)
                set.remove(nums[i-k-1]);
            if (!set.add(nums[i]))
                return true;
        }
        return false;
    }
}

 

posted @ 2017-02-15 16:24  细雨落花  阅读(218)  评论(0编辑  收藏  举报