442. Find All Duplicates in an Array--找到数组中出现两次的数字
来源:互联网 发布:网络三字经全文解释 编辑:程序博客网 时间:2024/06/05 11:00
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]
题目的意思很明显了,找到数组中出现次数为2的数字,返回这些数字即可。我用了HashMap,将每个数字和它出现的次数作为一个映射,然后遍历map,将符合条件的值添加到list中即可。虽然AC了,但是只击败了4.8%的提交结果==,代码如下:
List<Integer> list = new ArrayList<Integer>(); Map<Integer,Integer> map = new HashMap<>(); for(int i=0;i<nums.length;i++){ if(!map.containsKey(nums[i])){ map.put(nums[i], 1); } else{map.put(nums[i],map.get(nums[i])+1);} } for(Map.Entry<Integer,Integer> m:map.entrySet()) if(m.getValue()==2){ list.add(m.getKey()); } return list;网上看了另一种方法,充分应用条件,因为题目中说明,这些数字1 ≤ a[i] ≤ n (n = size of array),并且一些数字出现2次,其他的出现1次,那么,新建一个数组,把nums中的数字nums[i]放到temp中索引为nums[i]的地方,如果temp[nums[i]]=nums[i],说明nums[i]之前已经出现过,那么就将它加入到res这个列表中,提交结果为60%左右。代码如下:
int [] temp = new int [nums.length+1];List<Integer> res = new ArrayList<>();for(int i=0;i<nums.length;i++){if(temp[nums[i]]==nums[i]){res.add(nums[i]);}else{temp[nums[i]]=nums[i];}}return res;
阅读全文
0 0
- 442. Find All Duplicates in an Array--找到数组中出现两次的数字
- LeetCode--Find All Numbers Disappeared in an Array(找到数组中未出现的数字)
- leetcode_442. Find All Duplicates in an Array 找数组中出现两次的数,正负号标记法
- Leetcode:442. Find All Duplicates in an Array 找数组中的重复数字
- 448 Find All Numbers Disappeared in an Array找到[1,n]内没有出现的数字
- 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
- Python socket网络编程4
- Android融云会话及会话列表的实现
- C/C++ 中const关键字总结
- 数字图像处理:基于MATLAB的车牌识别项目
- Linux常用命令学习----(初级命令)
- 442. Find All Duplicates in an Array--找到数组中出现两次的数字
- 互斥,同步,信号量,管程概述
- Java面试题集(第一部分)(1-50)
- HTML==小试牛刀
- [Cordova/Phonegap] 一位程序猿朋友封装的Cordova插件
- BZOJ 1192-鬼谷子的钱袋
- linux部署服务器遇到的问题(一)
- 巧用短路逻辑优化代码质量
- Android蓝牙健康设备开发:Health Device Profile(HDP)