給定一個整數數組,1 ≤ a[i] ≤ n(n = 數組的大小)滑频,一些元素出現兩次,其他元素出現一次唤冈。
找到在此數組中出現兩次的所有元素峡迷。
find-all-duplicates-in-an-array
樣例
樣例1
輸入:
[4,3,2,7,8,2,3,1]
輸出:
[2,3]
樣例2
輸入:
[10,2,5,10,9,1,1,4,3,7]
輸出:
[1,10]
分析求數組中出現的重復數字
思路1、遍歷數組,使用map 存儲數組中的元素跟個數
遍歷 map val 大于1 的存到 集合就好
思路2绘搞、
我們發(fā)現對數組的所有元素均有1 <= a[i] <=n ,也就是說對于所有a[a[i]-1]均為合法下標彤避。由此引出如下做法:
對于每個a[i],我們將其對應的a[a[i]-1]取相反數夯辖,如果已經為負數則將a[i]加入答案中琉预。
public class Solution {
/**
* @param nums: a list of integers
* @return: return a list of integers
*/
public List<Integer> findDuplicates(int[] nums) {
// write your code here
if (nums == null || nums.length == 0) {
return null;
}
Map<Integer,Integer> map = new HashMap<>();
for (int num : nums) {
map.put(num, map.getOrDefault(num, 0) + 1);
}
List<Integer> list = new ArrayList<>();
for (Integer key : map.keySet()) {
if (map.get(key)>1) {
list.add(key);
}
}
return list;
}
}
public class Solution {
/**
* @param nums: a list of integers
* @return: return a list of integers
*/
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(nums[i]));
} else {
nums[index] = -nums[index];
}
}
return res;
}
}