+ 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 Answers
+ 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