217. Contains Duplicate数组重复元素 123

[抄题]:

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.

 [暴力解法]:

时间分析:n^2

空间分析:1

 [优化后]:

时间分析:nlgn

空间分析:1

[奇葩输出条件]:

[奇葩corner case]:

[思维问题]:

[一句话思路]:

 双重指针必须联想到用前向窗口优化

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

[一刷]:

[二刷]:

[三刷]:

[四刷]:

[五刷]:

  [五分钟肉眼debug的结果]:

[总结]:

 双重指针必须联想到用前向窗口优化

[复杂度]:Time complexity: O(nlgn) Space complexity: O(n)

[英文数据结构或算法,为什么不用别的数据结构或算法]:

[关键模板化代码]:

[其他解法]:

[Follow Up]:

[LC给出的题目变变变]:

 [代码风格] :

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

[抄题]:

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.

 [暴力解法]:

时间分析:

空间分析:

 [优化后]:

时间分析:

空间分析:

[奇葩输出条件]:

[奇葩corner case]:

[思维问题]:

不能直接-1定范围了,只能用hashset

[一句话思路]:

每次都往窗口中去掉左边界,添加自己

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

[一刷]:

  1. 强化区别意识:元素一直要加,index > k 才加
  2. +1, -1需要试试

[二刷]:

[三刷]:

[四刷]:

[五刷]:

  [五分钟肉眼debug的结果]:

[总结]:

  1. 强化区别意识:元素一直要加,index > k 才加

[复杂度]:Time complexity: O(n) Space complexity: O(n)

[英文数据结构或算法,为什么不用别的数据结构或算法]:

[关键模板化代码]:

[其他解法]:

[Follow Up]:

[LC给出的题目变变变]:

 [代码风格] :

class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        //cc
        if (nums.length == 0 || nums == null) {
            return false;
        }
        
        //ini = sort
        Set<Integer> set = new HashSet<>();
        
        //for
        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
        return false;
    }
}
View Code
原文地址:https://www.cnblogs.com/immiao0319/p/8848042.html