leetcode系列(二):contains duplicate

来源:互联网 发布:结构弯矩计算软件 编辑:程序博客网 时间:2024/06/06 12:53

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.

教程解析

线性查找:最naive的解法

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

这种解法的时间复杂度是O(N^2),空间复杂度是O(1).但是leetcode上面有这样的规定
Note

This approach will get Time Limit Exceeded on LeetCode. Usually, if an algorithm is O(n^2)O(n
2
), it can handle nn up to around 10^410
4
. It gets Time Limit Exceeded when n \geq 10^5n≥10
5
.

sorting

通过先排序在比较前后的两个数是否相等。

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

时间复杂度是O(nlgn)。因为这里的排序是优化过的,最多只能O(nlgn),遍历是O(n)。空间复杂度为1

hashmap法

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

事件复杂度为O(n),空间复杂度为O(n).比较简单。

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 difference between i and j is at most k.

我的naive解法:O(n^2)

 public boolean containsNearbyDuplicate(int[] nums, int k) {        ArrayList<Integer> list=new ArrayList<Integer>();        for(int num:nums){            if(!list.contains(num)){                list.add(num);            }else{                int size=list.size();                for(int i=0;i<k;i++){                    if(size-1-i<0) break;                    if(nums[size-1-i]==num) return true;                }                list.add(num);            }        }        return false;    }

当数据到达10^4时就会崩,就和上面一样。但是自己实在想不到好的解法了。

优秀解法

public boolean containsNearbyDuplicate(int[] nums, int k) {        Set<Integer> set = new HashSet<Integer>();        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; }

如果i

public boolean containsNearbyDuplicate(int[] nums, int k) {    Map<Integer, Integer> map = new HashMap<Integer, Integer>();    for (int i = 0; i < nums.length; i++) {        if (map.containsKey(nums[i])) {            if (i - map.get(nums[i]) <= k) return true;        }        map.put(nums[i], i);    }    return false;}
0 0
原创粉丝点击