Add to List 442. Find All Duplicates in an Array(java)
来源:互联网 发布:ios屏蔽广告软件 编辑:程序博客网 时间:2024/05/17 10:56
题目
Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements that appear twice in this array.
Could you do it without extra space and in O(n) runtime?
Example: Input: [4,3,2,7,8,2,3,1]
Output: [2,3]
题目要求 :给的验证数组最多出现两次相同的数,或者出现一次某个数,要求不开辟空间,时间复杂度是O(n)。
因为数组输入的特点 1<=sums[i]<=n,则可以把原数组当hash表用 ,因为原数组是正数,标为负数表示出现过,如果遇到负数 就表示第二次出现,就可以找出所有出现过2次的数
public class Solution { public List<Integer> findDuplicates(int[] nums) { int length = nums.length; List<Integer> list = new ArrayList<Integer>(); for (int i = 0; i < length; i++) { int val = Math.abs(nums[i]) - 1; if (nums[val] > 0) { nums[val] = -nums[val]; }else { list.add(Math.abs(nums[i])); } } return list; }}
阅读全文
0 0
- Add to List 442. Find All Duplicates in an Array(java)
- leetcode Add to List 442. 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
- 442. 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
- 442. 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
- 442. 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
- 442. Find All Duplicates in an Array
- 蓝牙模块调试笔记
- 51nod 1580 铺管道
- Android 创建自定义控件
- 单例模式之:高效非同步方法实现
- 克隆创建PDB--(1)本地克隆创建PDB
- Add to List 442. Find All Duplicates in an Array(java)
- win7下IIS配置以及域名映射方法
- Python-元类
- codeforces 271A(Beautiful Year) Java
- MongoDB详细介绍
- JDBC的业务逻辑流程和模块开发的原理分析
- Java基础的编程:9*9乘法表、质数的寻找、scanner的使用和迭代的基础
- Hibernate之HQL总结
- Android图片处理框架之Glide学习使用