532. K-diff Pairs in an Array绝对值差为k的数组对
[抄题]:
Given an array of integers and an integer k, you need to find the number of unique k-diff pairs in the array. Here a k-diff pair is defined as an integer pair (i, j), where i and j are both numbers in the array and their absolute difference is k.
[暴力解法]:
时间分析:
空间分析:
[优化后]:
时间分析:
空间分析:
[奇葩输出条件]:
[奇葩corner case]:
[思维问题]:
以为找k只能取两边:带数据进去看一下就知道了
[一句话思路]:
右边界的循环在左边界的循环以内控制
[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):
[画图]:
[一刷]:
- 0< i < nums.length,说最后一次
- 用指针的时候要提前确认一下指针范围,否则会莫名报错。忘了
- 左窗口可能一直重复,eg 11111,用while去重。头一次见
[二刷]:
[三刷]:
[四刷]:
[五刷]:
[五分钟肉眼debug的结果]:
[总结]:
右边界的循环在左边界的循环以内控制
[复杂度]:Time complexity: O(每个左边界都对应新一半中的右边界nlgn) Space complexity: O(1)
[英文数据结构或算法,为什么不用别的数据结构或算法]:
[关键模板化代码]:
右边界在左边界之内:
for (int i = 0, j = 0; i < nums.length; i++) { for (j = Math.max(j, i + 1); j < nums.length && nums[j] - nums[i] < k; j++);
[其他解法]:
[Follow Up]:
[LC给出的题目变变变]:
[代码风格] :
class Solution { public int findPairs(int[] nums, int k) { //cc if (nums == null || nums.length == 0) { return 0; } //ini int count = 0; //sort Arrays.sort(nums); //for for (int i = 0, j = 0; i < nums.length; i++) { for (j = Math.max(j, i + 1); j < nums.length && nums[j] - nums[i] < k; j++); if (j < nums.length && nums[j] - nums[i] == k) count++; while (i + 1 < nums.length && nums[i + 1] == nums[i]) i++; } //return return count; } }