Home > Java > JavaBase > body text

How to find unique numbers in an array in java

王林
Release: 2019-12-09 16:14:46
Original
4969 people have browsed it

How to find unique numbers in an array in java

Find a non-repeating number in the array. The question is roughly like this:

int[] a = { 1, 2, 3, 4, 3, 2, 1 };
Copy after login

Recommended online video tutorial: java online learning

The solution is:

public static int getNoRepeat() {
	int[] a = { 1, 2, 3, 4, 3, 2, 1 };
	for (int i = 0; i < a.length; i++) {
		int b = 0;
		for (int j = 0; j < a.length; j++) {
			if (a[i] == a[j]) {
				b++;
			}
		}
		if (b == 1) {
			return a[i];
		}
	}
	return 0;
}
Copy after login

The idea is to compare the first number in the array with each number in the array. If the same number is equal to 2, it is repeated, and if it is equal to 1, it is not Repeated.

If you want to find repeated numbers, just replace b==1 with b==2.

Recommended related articles and tutorials: java quick start

The above is the detailed content of How to find unique numbers in an array in java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template