博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Find All Duplicates in an Array
阅读量:4364 次
发布时间:2019-06-07

本文共 798 字,大约阅读时间需要 2 分钟。

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]
1 public class Solution { 2     //使用index和负数来表示这个位置被访问过。 3  4     public List
findDuplicates(int[] nums) { 5 List
res = new ArrayList<>(); 6 for (int i = 0; i < nums.length; ++i) { 7 int index = Math.abs(nums[i]) - 1; 8 if (nums[index] < 0) { 9 res.add(Math.abs(index + 1));10 }11 nums[index] = -nums[index];12 }13 return res;14 }15 }

 

转载于:https://www.cnblogs.com/beiyeqingteng/p/6236054.html

你可能感兴趣的文章
【DBAplus】SQL优化:一篇文章说清楚Oracle Hint的正确使用姿势
查看>>
二叉树结点删除操作
查看>>
图论-单源最短路-SPFA算法
查看>>
转换文件的字符集
查看>>
软件质量理解
查看>>
jquery 在 table 中修改某行值
查看>>
pyc文件是什么【转载】
查看>>
POM.xml 标签详解
查看>>
hdu 3635 Dragon Balls (并查集)
查看>>
文件操作
查看>>
7.java集合,泛型简单总结,IO流
查看>>
杭电2007 平方和与立方和
查看>>
JS邮箱验证-正则验证
查看>>
Quartz 2D绘图
查看>>
JS Fetch
查看>>
EJB 笔记
查看>>
【delete】Android自定义控件(四) 自定义ImageView动态设置ImageView的高度
查看>>
HDUOJ------(1230)火星A+B
查看>>
Servlet
查看>>
基于jquery地图特效全国网点查看代码
查看>>