+ 6
java solve problem(i has no idea how to solve it,need help ....)
Write a Java program to remove the duplicate elements of a given array and return the new length of the array. Sample array: [20, 20, 30, 40, 50, 50, 50] After removing the duplicate elements the program should return 4 as the new length of the array. How the length is 4? check below 20,20 30 40 50,50,50 \ | | / Length = 1 + 1 + 1 + 1 =4
13 Respostas
+ 5
It just asks the number of distinct element of an array. So what is the problem with getting 4?
Anyway, I prefer using stream instead of hashset as Sick Line BrođĄïž said
Arrays.stream(new int[]{20,20,30,40,50,50,50}).distinct() //will return a stream with unique values
+ 5
Rael Sick Line BrođĄïž this way will work on unsorted arrays if you want to solve this in a more programmatic way without using streams or hashsets. I just used arraylists for ease.
var a = new int[] {10,40,50,20,10,30,40};
var unique = new java.util.ArrayList<Integer>();
for (var i:a) {
if (!unique.contains(i)){
unique.add(i);
}
}
System.out.println("Unique ones: "+unique);
System.out.println("Length: "+unique.size());
+ 4
can you please check Rael đ
https://code.sololearn.com/c4fb86NoZLTj/?ref=app
+ 3
Sick Line BrođĄïž then learn it bro! It's a superb powerful package which can ve helpful in many analysis and computation task!
And mmm.. your example code judge an element as unique only if the following 1 is not equal to it. If {10,24,24,10} or something like that is provided the method fails.
+ 2
Sick Line BrođĄïž To check the element , like this?
For(int i = 0;i < arr.length;i++)
{
for(int x = i+1;x < arr.length;x++){
if(arr(i) == arr(x))
+ 2
Sick Line BrođĄïž Oh ok!
+ 1
SΔηÎčrÏ
Ïαsαη i took this question on website.The website got it solution,but the owner of website make a wrong solution.
But the answer is 4 ,because it find the duplicate value and compare it into one element so thats how the length get
+ 1
Sick Line BrođĄïž i knew it ,just forgot to delete the comments :D