Problem:
Remove the duplicate elements from an ordered array.
Solution:
package array.programs;
import java.util.Arrays;
import java.util.Scanner;
public class RemovalOfDuplicatesFromAnArray {
int[] numbers;
int max;
public static void main(String[] args) {
RemovalOfDuplicatesFromAnArray removalOfDuplicatesFromAnArray = new RemovalOfDuplicatesFromAnArray();
removalOfDuplicatesFromAnArray.getTheNumbers();
removalOfDuplicatesFromAnArray.removeDuplicates();
removalOfDuplicatesFromAnArray.printTheResult();
}
public void getTheNumbers(){
Scanner scanner = new Scanner(System.in);
System.out.println("how many numbers");
numbers = new int[scanner.nextInt()];
for (int i = 0; i < numbers.length; i++) {
System.out.println("enter number");
numbers[i] = scanner.nextInt();
}
scanner.close();
}
public void removeDuplicates(){
Arrays.sort(numbers);
int j = 0;
int[] temp = new int[numbers.length];
for (int i = 0; i < numbers.length - 1; i++) {
if(numbers[i] != numbers[i+1]){
temp[j++] = numbers[i];
}
}
temp[j++] = numbers[numbers.length - 1];
for (int i = 0; i < temp.length; i++) {
numbers[i] = temp[i];
}
}
public void printTheResult(){
for (int i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
}
}
}
Output:
how many numbers
10
enter number
12
enter number
33
enter number
22
enter number
333
enter number
12
enter number
333
enter number
444
enter number
222
enter number
33
enter number
44
12 22 33 44 222 333 444 0 0 0
Remove the duplicate elements from an ordered array.
Solution:
package array.programs;
import java.util.Arrays;
import java.util.Scanner;
public class RemovalOfDuplicatesFromAnArray {
int[] numbers;
int max;
public static void main(String[] args) {
RemovalOfDuplicatesFromAnArray removalOfDuplicatesFromAnArray = new RemovalOfDuplicatesFromAnArray();
removalOfDuplicatesFromAnArray.getTheNumbers();
removalOfDuplicatesFromAnArray.removeDuplicates();
removalOfDuplicatesFromAnArray.printTheResult();
}
public void getTheNumbers(){
Scanner scanner = new Scanner(System.in);
System.out.println("how many numbers");
numbers = new int[scanner.nextInt()];
for (int i = 0; i < numbers.length; i++) {
System.out.println("enter number");
numbers[i] = scanner.nextInt();
}
scanner.close();
}
public void removeDuplicates(){
Arrays.sort(numbers);
int j = 0;
int[] temp = new int[numbers.length];
for (int i = 0; i < numbers.length - 1; i++) {
if(numbers[i] != numbers[i+1]){
temp[j++] = numbers[i];
}
}
temp[j++] = numbers[numbers.length - 1];
for (int i = 0; i < temp.length; i++) {
numbers[i] = temp[i];
}
}
public void printTheResult(){
for (int i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
}
}
}
Output:
how many numbers
10
enter number
12
enter number
33
enter number
22
enter number
333
enter number
12
enter number
333
enter number
444
enter number
222
enter number
33
enter number
44
12 22 33 44 222 333 444 0 0 0
No comments:
Post a Comment