I am Java beginner, I found a few topics regarding this theme, but none of them worked for me. I have an array like this:
我是Java初学者,我发现了一些关于这个主题的主题,但是没有一个对我有用。我有一个这样的数组:
int[] numbers = {1, 1, 2, 1, 3, 4, 5};
and I would need to get this output:
我需要得到这个输出:
1, 2, 3, 4, 5
Every item from that array just once.
数组中的每一项都只有一次。
But how to get it?
但是如何得到它呢?
14 个解决方案
#1
11
The simpliest solution without writing your own algorithm:
最简单的解决方案,无需编写自己的算法:
Integer[] numbers = {1, 1, 2, 1, 3, 4, 5};
Set<Integer> uniqKeys = new TreeSet<Integer>();
uniqKeys.addAll(Arrays.asList(numbers));
System.out.println("uniqKeys: " + uniqKeys);
Set interface guarantee uniqueness of values. TreeSet additionally sorts this values.
设置接口保证值的唯一性。TreeSet还对这些值进行了排序。
#2
7
You can use a Set<Integer>
and save lot of time since it holds unique elements. If you aren't allowed to use any class from Java Collections, sort the array and count the unique elements. You can sort the array manually or use Arrays#sort
.
您可以使用Set
I'll post the Set<Integer>
code:
设置
int[] numbers = {1, 1, 2, 1, 3, 4, 5};
Set<Integer> setUniqueNumbers = new LinkedHashSet<Integer>();
for(int x : numbers) {
setUniqueNumbers.add(x);
}
for(Integer x : setUniqueNumbers) {
System.out.println(x);
}
Note that I prefer to use LinkedHashSet
as Set implementation since it maintains the order of how the elements were inserted. This means, if your array was {2 , 1 , 2}
then the output will be 2, 1
and not 1, 2
.
注意,我倾向于使用LinkedHashSet作为Set实现,因为它维护了元素的插入顺序。这意味着,如果你的数组是{2,1,2}那么输出将是2 1而不是1 2。
#3
3
In Java 8:
在Java 8:
final int[] expected = { 1, 2, 3, 4, 5 };
final int[] numbers = { 1, 1, 2, 1, 3, 4, 5 };
final int[] distinct = Arrays.stream(numbers)
.distinct()
.toArray();
Assert.assertArrayEquals(Arrays.toString(distinct), expected, distinct);
final int[] unorderedNumbers = { 5, 1, 2, 1, 4, 3, 5 };
final int[] distinctOrdered = Arrays.stream(unorderedNumbers)
.sorted()
.distinct()
.toArray();
Assert.assertArrayEquals(Arrays.toString(distinctOrdered), expected, distinctOrdered);
#4
2
//Running total of distinct integers found
int distinctIntegers = 0;
for (int j = 0; j < array.length; j++)
{
//Get the next integer to check
int thisInt = array[j];
//Check if we've seen it before (by checking all array indexes below j)
boolean seenThisIntBefore = false;
for (int i = 0; i < j; i++)
{
if (thisInt == array[i])
{
seenThisIntBefore = true;
}
}
//If we have not seen the integer before, increment the running total of distinct integers
if (!seenThisIntBefore)
{
distinctIntegers++;
}
}
#5
2
Below code will print unique integers have a look:
下面的代码将打印唯一的整数:
printUniqueInteger(new int[]{1, 1, 2, 1, 3, 4, 5});
static void printUniqueInteger(int array[]){
HashMap<Integer, String> map = new HashMap();
for(int i = 0; i < array.length; i++){
map.put(array[i], "test");
}
for(Integer key : map.keySet()){
System.out.println(key);
}
}
#6
2
public class Practice {
public static void main(String[] args) {
List<Integer> list = new LinkedList<>(Arrays.asList(3,7,3,-1,2,3,7,2,15,15));
countUnique(list);
}
public static void countUnique(List<Integer> list){
Collections.sort(list);
Set<Integer> uniqueNumbers = new HashSet<Integer>(list);
System.out.println(uniqueNumbers.size());
}
}
}
#7
1
Simple Hashing will be far efficient and faster than any Java inbuilt function:
简单的哈希将比任何Java内建函数都高效和快速:
public class Main
{
static int HASH[];
public static void main(String[] args)
{
int[] numbers = {1, 1, 2, 1, 3, 4, 5};
HASH=new int[100000];
for(int i=0;i<numbers.length;i++)
{
if(HASH[numbers[i]]==0)
{
System.out.print(numbers[i]+",");
HASH[numbers[i]]=1;
}
}
}
}
Time Complexity: O(N), where N=numbers.length
时间复杂度:O(N),其中N=number .length
演示
#8
0
You could do it like this:
你可以这样做:
int[] numbers = {1, 1, 2, 1, 3, 4, 5};
ArrayList<Integer> store = new ArrayList<Integer>(); // so the size can vary
for (int n = 0; n < numbers.length; n++){
if (!store.contains(numbers[n])){ // if numbers[n] is not in store, then add it
store.add(numbers[n]);
}
}
numbers = new int[store.size()];
for (int n = 0; n < store.size(); n++){
numbers[n] = store.get(n);
}
Integer and int can be (almost) used interchangeably. This piece of code takes your array "numbers" and changes it so that all duplicate numbers are lost. If you want to sort it, you can add Collections.sort(store);
before numbers = new int[store.size()]
整数和整数可以(几乎)互换使用。这段代码获取数组的“数字”,并对其进行修改,从而丢失所有重复的数字。如果您想对它进行排序,您可以添加Collections.sort(存储);之前的数字=新int[store.size()]
#9
0
I don't know if you've solved your issue yet, but my code would be:
我不知道你是否已经解决了你的问题,但是我的代码是:
int[] numbers = {1, 1, 2, 1, 3, 4, 5};
int x = numbers.length;
int[] unique = new int[x];
int p = 0;
for(int i = 0; i < x; i++)
{
int temp = numbers[i];
int b = 0;
for(int y = 0; y < x; y++)
{
if(unique[y] != temp)
{
b++;
}
}
if(b == x)
{
unique[p] = temp;
p++;
}
}
for(int a = 0; a < p; a++)
{
System.out.print(unique[a]);
if(a < p-1)
{
System.out.print(", ");
}
}
#10
0
String s1[]= {"hello","hi","j2ee","j2ee","sql","jdbc","hello","jdbc","hybernet","j2ee"};
int c=0;
for(int i=0;i<s1.length;i++)
{
for(int j=i+1;j<s1.length;j++)
{
if(s1[i]==(s1[j]) )
{
c++;
}
}
if(c==0)
{
System.out.println(s1[i]);
}
else
{
c=0;
}
}
}
}
#11
0
To find out unique data:
找出唯一的数据:
public class Uniquedata
{
public static void main(String[] args)
{
int c=0;
String s1[]={"hello","hi","j2ee","j2ee","sql","jdbc","hello","jdbc","hybernet","j2ee","hello","hello","hybernet"};
for(int i=0;i<s1.length;i++)
{
for(int j=i+1;j<s1.length;j++)
{
if(s1[i]==(s1[j]) )
{
c++;
s1[j]="";
}}
if(c==0)
{
System.out.println(s1[i]);
}
else
{
s1[i]="";
c=0;
}
}
}
}
#12
0
you can use
您可以使用
Object[] array = new HashSet<>(Arrays.asList(numbers)).toArray();
#13
0
Here is my piece of code using counting sort (partially)
这是我使用计数排序(部分)的代码
Output is a sorted array consiting of unique elements
输出是由唯一元素组成的排序数组
void findUniqueElementsInArray(int arr[]) {
int[] count = new int[256];
int outputArrayLength = 0;
for (int i = 0; i < arr.length; i++) {
if (count[arr[i]] < 1) {
count[arr[i]] = count[arr[i]] + 1;
outputArrayLength++;
}
}
for (int i = 1; i < 256; i++) {
count[i] = count[i] + count[i - 1];
}
int[] sortedArray = new int[outputArrayLength];
for (int i = 0; i < arr.length; i++) {
sortedArray[count[arr[i]] - 1] = arr[i];
}
for (int i = 0; i < sortedArray.length; i++) {
System.out.println(sortedArray[i]);
}
}
Reference - discovered this solution while trying to solve a problem from HackerEarth
参考-在尝试解决来自HackerEarth的问题时发现了这个解决方案
#14
-1
public class DistinctArray {
public static void main(String[] args) {
int num[]={1,2,5,4,1,2,3,5};
for(int i =0;i<num.length;i++)
{
boolean isDistinct=false;
for(int j=0;j<i;j++)
{
if(num[j]==num[i])
{
isDistinct=true;
break;
}
}
if(!isDistinct)
{
System.out.print(num[i]+" ");
}
}
}
}
#1
11
The simpliest solution without writing your own algorithm:
最简单的解决方案,无需编写自己的算法:
Integer[] numbers = {1, 1, 2, 1, 3, 4, 5};
Set<Integer> uniqKeys = new TreeSet<Integer>();
uniqKeys.addAll(Arrays.asList(numbers));
System.out.println("uniqKeys: " + uniqKeys);
Set interface guarantee uniqueness of values. TreeSet additionally sorts this values.
设置接口保证值的唯一性。TreeSet还对这些值进行了排序。
#2
7
You can use a Set<Integer>
and save lot of time since it holds unique elements. If you aren't allowed to use any class from Java Collections, sort the array and count the unique elements. You can sort the array manually or use Arrays#sort
.
您可以使用Set
I'll post the Set<Integer>
code:
设置
int[] numbers = {1, 1, 2, 1, 3, 4, 5};
Set<Integer> setUniqueNumbers = new LinkedHashSet<Integer>();
for(int x : numbers) {
setUniqueNumbers.add(x);
}
for(Integer x : setUniqueNumbers) {
System.out.println(x);
}
Note that I prefer to use LinkedHashSet
as Set implementation since it maintains the order of how the elements were inserted. This means, if your array was {2 , 1 , 2}
then the output will be 2, 1
and not 1, 2
.
注意,我倾向于使用LinkedHashSet作为Set实现,因为它维护了元素的插入顺序。这意味着,如果你的数组是{2,1,2}那么输出将是2 1而不是1 2。
#3
3
In Java 8:
在Java 8:
final int[] expected = { 1, 2, 3, 4, 5 };
final int[] numbers = { 1, 1, 2, 1, 3, 4, 5 };
final int[] distinct = Arrays.stream(numbers)
.distinct()
.toArray();
Assert.assertArrayEquals(Arrays.toString(distinct), expected, distinct);
final int[] unorderedNumbers = { 5, 1, 2, 1, 4, 3, 5 };
final int[] distinctOrdered = Arrays.stream(unorderedNumbers)
.sorted()
.distinct()
.toArray();
Assert.assertArrayEquals(Arrays.toString(distinctOrdered), expected, distinctOrdered);
#4
2
//Running total of distinct integers found
int distinctIntegers = 0;
for (int j = 0; j < array.length; j++)
{
//Get the next integer to check
int thisInt = array[j];
//Check if we've seen it before (by checking all array indexes below j)
boolean seenThisIntBefore = false;
for (int i = 0; i < j; i++)
{
if (thisInt == array[i])
{
seenThisIntBefore = true;
}
}
//If we have not seen the integer before, increment the running total of distinct integers
if (!seenThisIntBefore)
{
distinctIntegers++;
}
}
#5
2
Below code will print unique integers have a look:
下面的代码将打印唯一的整数:
printUniqueInteger(new int[]{1, 1, 2, 1, 3, 4, 5});
static void printUniqueInteger(int array[]){
HashMap<Integer, String> map = new HashMap();
for(int i = 0; i < array.length; i++){
map.put(array[i], "test");
}
for(Integer key : map.keySet()){
System.out.println(key);
}
}
#6
2
public class Practice {
public static void main(String[] args) {
List<Integer> list = new LinkedList<>(Arrays.asList(3,7,3,-1,2,3,7,2,15,15));
countUnique(list);
}
public static void countUnique(List<Integer> list){
Collections.sort(list);
Set<Integer> uniqueNumbers = new HashSet<Integer>(list);
System.out.println(uniqueNumbers.size());
}
}
}
#7
1
Simple Hashing will be far efficient and faster than any Java inbuilt function:
简单的哈希将比任何Java内建函数都高效和快速:
public class Main
{
static int HASH[];
public static void main(String[] args)
{
int[] numbers = {1, 1, 2, 1, 3, 4, 5};
HASH=new int[100000];
for(int i=0;i<numbers.length;i++)
{
if(HASH[numbers[i]]==0)
{
System.out.print(numbers[i]+",");
HASH[numbers[i]]=1;
}
}
}
}
Time Complexity: O(N), where N=numbers.length
时间复杂度:O(N),其中N=number .length
演示
#8
0
You could do it like this:
你可以这样做:
int[] numbers = {1, 1, 2, 1, 3, 4, 5};
ArrayList<Integer> store = new ArrayList<Integer>(); // so the size can vary
for (int n = 0; n < numbers.length; n++){
if (!store.contains(numbers[n])){ // if numbers[n] is not in store, then add it
store.add(numbers[n]);
}
}
numbers = new int[store.size()];
for (int n = 0; n < store.size(); n++){
numbers[n] = store.get(n);
}
Integer and int can be (almost) used interchangeably. This piece of code takes your array "numbers" and changes it so that all duplicate numbers are lost. If you want to sort it, you can add Collections.sort(store);
before numbers = new int[store.size()]
整数和整数可以(几乎)互换使用。这段代码获取数组的“数字”,并对其进行修改,从而丢失所有重复的数字。如果您想对它进行排序,您可以添加Collections.sort(存储);之前的数字=新int[store.size()]
#9
0
I don't know if you've solved your issue yet, but my code would be:
我不知道你是否已经解决了你的问题,但是我的代码是:
int[] numbers = {1, 1, 2, 1, 3, 4, 5};
int x = numbers.length;
int[] unique = new int[x];
int p = 0;
for(int i = 0; i < x; i++)
{
int temp = numbers[i];
int b = 0;
for(int y = 0; y < x; y++)
{
if(unique[y] != temp)
{
b++;
}
}
if(b == x)
{
unique[p] = temp;
p++;
}
}
for(int a = 0; a < p; a++)
{
System.out.print(unique[a]);
if(a < p-1)
{
System.out.print(", ");
}
}
#10
0
String s1[]= {"hello","hi","j2ee","j2ee","sql","jdbc","hello","jdbc","hybernet","j2ee"};
int c=0;
for(int i=0;i<s1.length;i++)
{
for(int j=i+1;j<s1.length;j++)
{
if(s1[i]==(s1[j]) )
{
c++;
}
}
if(c==0)
{
System.out.println(s1[i]);
}
else
{
c=0;
}
}
}
}
#11
0
To find out unique data:
找出唯一的数据:
public class Uniquedata
{
public static void main(String[] args)
{
int c=0;
String s1[]={"hello","hi","j2ee","j2ee","sql","jdbc","hello","jdbc","hybernet","j2ee","hello","hello","hybernet"};
for(int i=0;i<s1.length;i++)
{
for(int j=i+1;j<s1.length;j++)
{
if(s1[i]==(s1[j]) )
{
c++;
s1[j]="";
}}
if(c==0)
{
System.out.println(s1[i]);
}
else
{
s1[i]="";
c=0;
}
}
}
}
#12
0
you can use
您可以使用
Object[] array = new HashSet<>(Arrays.asList(numbers)).toArray();
#13
0
Here is my piece of code using counting sort (partially)
这是我使用计数排序(部分)的代码
Output is a sorted array consiting of unique elements
输出是由唯一元素组成的排序数组
void findUniqueElementsInArray(int arr[]) {
int[] count = new int[256];
int outputArrayLength = 0;
for (int i = 0; i < arr.length; i++) {
if (count[arr[i]] < 1) {
count[arr[i]] = count[arr[i]] + 1;
outputArrayLength++;
}
}
for (int i = 1; i < 256; i++) {
count[i] = count[i] + count[i - 1];
}
int[] sortedArray = new int[outputArrayLength];
for (int i = 0; i < arr.length; i++) {
sortedArray[count[arr[i]] - 1] = arr[i];
}
for (int i = 0; i < sortedArray.length; i++) {
System.out.println(sortedArray[i]);
}
}
Reference - discovered this solution while trying to solve a problem from HackerEarth
参考-在尝试解决来自HackerEarth的问题时发现了这个解决方案
#14
-1
public class DistinctArray {
public static void main(String[] args) {
int num[]={1,2,5,4,1,2,3,5};
for(int i =0;i<num.length;i++)
{
boolean isDistinct=false;
for(int j=0;j<i;j++)
{
if(num[j]==num[i])
{
isDistinct=true;
break;
}
}
if(!isDistinct)
{
System.out.print(num[i]+" ");
}
}
}
}