+ 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

11th Jun 2019, 2:15 PM
Tzion
Tzion - avatar
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
11th Jun 2019, 2:27 PM
Seniru
Seniru - avatar
+ 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());
11th Jun 2019, 2:57 PM
Seniru
Seniru - avatar
11th Jun 2019, 5:22 PM
Pāˆ†WAN Māˆ†URYāˆ†
Pāˆ†WAN Māˆ†URYāˆ† - avatar
+ 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.
11th Jun 2019, 2:47 PM
Seniru
Seniru - avatar
+ 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))
11th Jun 2019, 2:32 PM
Tzion
Tzion - avatar
11th Jun 2019, 2:51 PM
Tzion
Tzion - avatar
+ 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
11th Jun 2019, 2:30 PM
Tzion
Tzion - avatar
+ 1
Sick Line BrošŸŒ”ļø i knew it ,just forgot to delete the comments :D
12th Jun 2019, 7:25 AM
Tzion
Tzion - avatar