leetcode_middle_6_442. Find All Duplicates in an Array
来源:互联网 发布:淘宝实时数据 编辑:程序博客网 时间:2024/05/17 08:30
题意:找出数列中出现两次的数字。(数列中每个数字的大小都是[1,nums.length])
分析:我们要做的是,找到出现不止一次(两次)的数字放入list中,这就要求我们在数字第二次出现的时候放入。
这就要求,我们需要能判断数字是第二次出现。
也就是需要某种标记,第一次出现的时候就标记,有这个标记才放入。
如果我们不用额外的空间的话,就只有数组的一个特色:角标可以利用。而且,我们要观察题目特征,对数值大小的限制也给我们提供了使用角标的充分性。
那么,第二个问题来了,怎么标记呢?
因为每个数字[1, nums.length],所以如果不是这些那么一定就是标记了,考虑标记为0:
一旦出现过(角标对应值是0)就放入list
一旦没出现过(角标对应值不是0)就标记为0
但是这样可能造成覆盖,让后面的数字变为0,所以为了维护数字本身的信息,又维护标记的信息,采取相反数的方法。
负号作为标记,而取绝对值又可以取得数字本身的信息,所以:
public class Solution { public List<Integer> findDuplicates(int[] nums) { List<Integer> res = new ArrayList<>(); for(int i = 0 ; i < nums.length; i++) { int n = Math.abs(nums[i]); if(nums[n - 1] < 0) res.add(n); else nums[n - 1] = - nums[n - 1]; } return res; }}
0 0
- leetcode_middle_6_442. Find All Duplicates in an Array
- 442. Find All Duplicates in an Array
- [LeetCode]Find All Duplicates in an Array
- LeetCode Find All Duplicates in an Array
- Leetcode442. Find All Duplicates in an Array
- 442. Find All Duplicates in an Array
- 442. Find All Duplicates in an Array
- Find All Duplicates in an Array
- 442. Find All Duplicates in an Array
- Leetcode Find All Duplicates in an Array
- 442. Find All Duplicates in an Array
- [Leetcode] Find All Duplicates in an Array
- 442. Find All Duplicates in an Array**
- 442. Find All Duplicates in an Array
- 442. Find All Duplicates in an Array
- Find All Duplicates in an Array
- 442. Find All Duplicates in an Array
- Find All Duplicates in an Array 题解
- Codeforces Round #256 (Div. 2)-C. Painting Fence
- SVN
- SQL Server-索引故事的遥远由来,原来是这样的?(二十八)
- PAT1063. 计算谱半径(20)
- SpringBoot缓存注解学习笔记之Redis
- leetcode_middle_6_442. Find All Duplicates in an Array
- 简述C语言重定向
- C语言 二叉树的遍历递归和(多种)非递归算法
- main函数
- C语言内存管理
- C/C++ 学习路线
- 强大的vim配置文件,让编程更随意
- ubuntu virtualbox xp 不能上网
- ubuntu 默认启动项和等待时间