217. Contains Duplicate数组重复元素 123

本文针对LeetCode上的两道经典题目提供了详细的解决方案。首先通过双重指针优化解决数组中是否存在重复元素的问题;其次利用HashSet实现判断数组中是否存在相隔不超过k距离的相同元素。文章深入剖析了两种解法的时间和空间复杂度。

[抄题]:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值