标签:重复项 beat view desc etc cheng this close color
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]
Java Solution:
Runtime beats 85.92%
完成日期:09/19/2017
关键词:Array
关键点:把num 和 num[num - 1] 做1对1的映射
1 class Solution 2 { 3 public List<Integer> findDuplicates(int[] nums) 4 { 5 List<Integer> duplicates = new ArrayList<>(); 6 7 for(int num: nums) 8 { 9 int absNum = Math.abs(num); 10 11 if(nums[absNum - 1] < 0) // if the number at position num - 1 is already negative 12 duplicates.add(absNum); // num is duplicate 13 else 14 nums[absNum - 1] *= -1; 15 } 16 17 return duplicates; 18 } 19 }
参考资料:
https://discuss.leetcode.com/topic/64735/java-simple-solution
LeetCode 题目列表 - LeetCode Questions List
LeetCode 442. Find All Duplicates in an Array (在数组中找到所有的重复项)
标签:重复项 beat view desc etc cheng this close color
原文地址:http://www.cnblogs.com/jimmycheng/p/7559612.html