LeetCode 442. Find All Duplicates in an Array
原题链接在这里:https://leetcode.com/problems/find-all-duplicates-in-an-array/
题目:
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]
题解:
类似Find All Numbers Disappeared in an Array. iterate nums array时把nums[Math.abs(nums[i]-1)]标负,但需要先检查是否已经标过负了。若是说明是出现过一次. 把index+1添加到res中.
Time Complexity: O(nums.length). Space: O(1).
AC Java:
1 public class Solution { 2 public List<Integer> findDuplicates(int[] nums) { 3 List<Integer> res = new ArrayList<Integer>(); 4 if(nums == null || nums.length == 0){ 5 return res; 6 } 7 8 for(int i = 0; i<nums.length; i++){ 9 int index = Math.abs(nums[i])-1; 10 if(nums[index] < 0){ 11 res.add(index + 1); 12 }else{ 13 nums[index] = -nums[index]; 14 } 15 } 16 return res; 17 } 18 }
可以吧num[i] swap到对应的index = nums[i]-1上面.
第二遍iterate时如果nums[i] !=i+1. nums[i]就是duplicate的. 加入res中.
Time Complexity: O(n). Space: O(1), regardless res.
AC Java:
1 class Solution { 2 public List<Integer> findDuplicates(int[] nums) { 3 List<Integer> res = new ArrayList<Integer>(); 4 for(int i = 0; i<nums.length; i++){ 5 if(nums[i]-1>=0 && nums[i]-1<nums.length && nums[i]!=nums[nums[i]-1]){ 6 swap(nums, i, nums[i]-1); 7 i--; 8 } 9 } 10 11 for(int i = 0; i<nums.length; i++){ 12 if(nums[i] != i+1){ 13 res.add(nums[i]); 14 } 15 } 16 17 return res; 18 } 19 20 private void swap(int [] nums, int i, int j){ 21 int temp = nums[i]; 22 nums[i] = nums[j]; 23 nums[j] = temp; 24 } 25 }
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步