【LeetCode】 442. Find All Duplicates in an Array
2017-01-06 08:54
204 查看
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:
public class Solution {
public List<Integer> findDuplicates(int[] nums) {
List<Integer> res = new ArrayList<>();
for (int i = 0; i < nums.length; i++) {
int index = Math.abs(nums[i]) - 1;
if (nums[index] < 0) {
res.add(Math.abs(index + 1));
} else {
nums[index] = -nums[index];
}
}
return res;
}
}
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]
public class Solution {
public List<Integer> findDuplicates(int[] nums) {
List<Integer> res = new ArrayList<>();
for (int i = 0; i < nums.length; i++) {
int index = Math.abs(nums[i]) - 1;
if (nums[index] < 0) {
res.add(Math.abs(index + 1));
} else {
nums[index] = -nums[index];
}
}
return res;
}
}
相关文章推荐
- 死磕微信!支付宝版“小程序”曝光
- <Principles of fMRI 1>课程笔记5--理解信号、噪音与血流
- 知乎爬虫之4:抓取页面数据
- 设计模式--状态模式(分布式中间件熔断器Java实现)
- BZOJ 1336&1337最小圆覆盖
- Object-C之Bug集中营
- BZOJ 1336&1337最小圆覆盖
- 一起学微软Power BI系列-使用技巧(5)自定义PowerBI时间日期表
- delphi pchar char byte string转换问题
- 启动oracle的三过程
- 李炎恢老师PHP第三季视频课程(设计模式+MVC模式+SMARTY+在线商城)
- 图片动画播放(AnimationDrawable)
- [置顶] 如何获取Android唯一标识(唯一序列号)
- HDU 2063 过山车(匈牙利算法)
- 建立docker私有仓库
- BZOJ 2424: [HAOI2010]订货
- 留的住的叫幸福,流逝的叫遗憾
- Linux内核模块开发基础【转】
- Android中手机录屏并转换GIF的两种方式
- 将list集合的元素按照添加顺序的倒序进行排列取出