本文介绍了如何从java中删除数组中的重复元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给我一些示例和代码,以便我以后可以试试
我尝试过:
i想要尝试这个但我无法获得精确的代码
Give me some example and codes for this so that i can try it later
What I have tried:
i want to try this but i cant get the excact code
推荐答案
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Java program to remove duplicates from this array. You don't
* need to physically delete duplicate elements, replacing with null, or
* empty or default value is ok.
*
* @author http://javarevisited.blogspot.com
*/
public class TechnicalInterviewTest {
private static final Logger logger = LoggerFactory.getLogger(TechnicalInterviewTest.class);
public static void main(String args[]) {
int[][] test = new int[][]{
{1, 1, 2, 2, 3, 4, 5},
{1, 1, 1, 1, 1, 1, 1},
{1, 2, 3, 4, 5, 6, 7},
{1, 2, 1, 1, 1, 1, 1},};
for (int[] input : test) {
System.out.println("Array with Duplicates : " + Arrays.toString(input));
System.out.println("After removing duplicates : " + Arrays.toString(removeDuplicates(input)));
}
}
/*
* Method to remove duplicates from array in Java, without using
* Collection classes e.g. Set or ArrayList. Algorithm for this
* method is simple, it first sort the array and then compare adjacent
* objects, leaving out duplicates, which is already in result.
*/
public static int[] removeDuplicates(int[] numbersWithDuplicates) {
// Sorting array to bring duplicates together
Arrays.sort(numbersWithDuplicates);
int[] result = new int[numbersWithDuplicates.length];
int previous = numbersWithDuplicates[0];
result[0] = previous;
for (int i = 1; i < numbersWithDuplicates.length; i++) {
int ch = numbersWithDuplicates[i];
if (previous != ch) {
result[i] = ch;
}
previous = ch;
}
return result;
}
}
Output :
Array with Duplicates : [1, 1, 2, 2, 3, 4, 5]
After removing duplicates : [1, 0, 2, 0, 3, 4, 5]
Array with Duplicates : [1, 1, 1, 1, 1, 1, 1]
After removing duplicates : [1, 0, 0, 0, 0, 0, 0]
Array with Duplicates : [1, 2, 3, 4, 5, 6, 7]
After removing duplicates : [1, 2, 3, 4, 5, 6, 7]
Array with Duplicates : [1, 2, 1, 1, 1, 1, 1]
After removing duplicates : [1, 0, 0, 0, 0, 0, 2]
import java.util.Arrays;
public class Removeduplicates {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] a = { 3, 1, 1, 4, 1, 4, 5 };
Arrays.sort(a);
int count = 0;
long start = System.currentTimeMillis();
for (int i = 0; i < a.length; i++) {
if (i + 1 < a.length && a[i] == a[i + 1]) {
count++;
}
}
int[] b = new int[a.length - count];
int c = 0;
for (int j = 0; j < a.length; j++) {
if (j + 1 < a.length && a[j] == a[j + 1]) {
} else {
b[c] = a[j];
c++;
}
}
a = b;
System.out.println(Arrays.toString(a) + "took"
+ (System.currentTimeMillis() - start));
}
}
这篇关于如何从java中删除数组中的重复元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!