[leetcode]442. Find all duplicates in an Array (Java)

Source: Internet
Author: User
Tags abs
question:

Given an array of integers, 1≤a[i]≤n (n = size of array) some elements appear twice and others appear.

Find all the elements which appear twice in this array.

Could do it without extra spaces and in O (n) runtime?

Example:

Input:
[4,3,2,7,8,2,3,1]

Output:
[2,3]
parsing:Method 1: According to the topic requirements: The validation array given up to two times the same number, or a certain number, the request does not open up space, time complexity is O (n). Because the array input features 1<=sums[i]<=n, you can use the original array as a hash table, because the original array is positive, marked with a negative number indicates that, if you encounter negative numbers that represent the second occurrence, you can find all the numbers that have occurred 2 times
public class Solution {public
list<integer> findduplicates (int[] nums) {	int length = Nums. length;
		list<integer> list = new arraylist<integer> ();
			for (int i = 0; i < length; i++) {
				int val = Math.Abs (Nums[i])-1;
				if (Nums[val] > 0) {
					Nums[val] =-nums[val];
				} else {
						List.add (Math.Abs (nums[i]));
						}
				
			
			return list;
	}

Method 2: If you open up a large memory space, redefine an array, assign a value of 0, and then the original array of the number of the new array corresponding to the index, each time +1;
public class Solution {
Public list<integer> findduplicates (int[] nums) {
int length = Nums.length;
		list<integer> list = new arraylist<integer> ();
		if (length = = 0) {return
			list;
		} else {
			int count[] = new Int[length];
			Arrays.fill (count, 0);
			for (int i = 0; i < length; i++) {
				count[nums[i]-1]++;
			}
			for (int j = 0; J < length; J +) {
				if (count[j] = = 2) {
					List.add (j + 1);
				}
			}
			return list;
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.