diff --git a/content/posts/leetcode.md b/content/posts/leetcode.md index 2f74579..59d55f1 100644 --- a/content/posts/leetcode.md +++ b/content/posts/leetcode.md @@ -2015,3 +2015,32 @@ func findDuplicate(nums []int) int { return slow } ``` + +## day28 2024-03-25 + +### 442. Find All Duplicates in an Array + +Given an integer array nums of length n where all the integers of nums are in the range [1, n] and each integer appears once or twice, return an array of all the integers that appears twice. + +You must write an algorithm that runs in O(n) time and uses only constant extra space. + +![03250qkp0rMB0Ms8](https://testingcf.jsdelivr.net/gh/game-loader/picbase@master/uPic/03250qkp0rMB0Ms8.png) + +### 题解 + +本题若想在O(n)时间复杂度内求解, 必须在遍历数组的时候充分利用遍历过的数据提供的信息, 在后续充分利用已有信息, 在本题中, 遍历过程中的每个位置处的数本身就是信息. 若使用O(n)的空间复杂度, 可以创建一个和目标数组长度相同的空数组, 将遍历到的元素的数作为下标, 设定对应空数组中下标所在位置的值作为标记. 这样后续遍历时看到标记则知道这个数是重复的. 若想空间复杂度为O(1), 因为本题并没有要求不修改数组, 可以修改数组中以这个数为下标处的数据, 这里可以将其取相反数来表明这个下标已经出现过. 这也是因为体重明确说明数组中的数的范围在1-数组长度之间, 因此可以采用这种方法来标记数据是否已经出现, 如果有数大小超过数组长度, 这种方案就不适用了, 则必须使用O(n)的空间. + +### 代码 + +```go +func findDuplicates(nums []int) []int { + result := []int{} + for _, values := range nums{ + if nums[int(math.Abs(float64(values)))-1] < 0{ + result = append(result, int(math.Abs(float64(values)))) + } + nums[int(math.Abs(float64(values)))-1] = -nums[int(math.Abs(float64(values)))-1] + } + return result +} +```