Удалить дубликаты из целочисленного массива
У меня проблема с кодированием этого:
Напишите статический метод с именем removeDuplicates
, который принимает в качестве входных данных массив целых чисел и возвращает в результате новый массив целых чисел с удалением всех дубликатов.
Например, если входной массив имеет элементы {4, 3, 3, 4, 5, 2, 4} результирующий массив
должен быть {4, 3, 5, 2}
Вот что я сделал до сих пор
public static int[] removeDuplicates(int []s){
int [] k = new int[s.length];
k[0]=s[0];
int m =1;
for(int i=1;i<s.length;++i){
if(s[i]!=s[i-1]){
k[m]=s[i];
++m;
}//endIF
}//endFori
return k;
}//endMethod
Ответы
Ответ 1
Чтобы сохранить порядок и удалить дубликаты в массиве integer, вы можете попробовать следующее:
public void removeDupInIntArray(int[] ints){
Set<Integer> setString = new LinkedHashSet<Integer>();
for(int i=0;i<ints.length;i++){
setString.add(ints[i]);
}
System.out.println(setString);
}
Надеюсь, что это поможет.
Ответ 2
попробуй это -
public static int[] removeDuplicates(int []s){
int result[] = new int[s.length], j=0;
for (int i : s) {
if(!isExists(result, i))
result[j++] = i;
}
return result;
}
private static boolean isExists(int[] array, int value){
for (int i : array) {
if(i==value)
return true;
}
return false;
}
Ответ 3
Прежде всего, вы должны знать длину без дубликатов (dups): начальная длина минус количество дубликатов.
Затем создайте новый массив с правильной длиной.
Затем проверьте каждый элемент списка [] для дубликатов, если dup основан - проверьте следующий элемент, если dup не создан - скопируйте элемент в новый массив.
public static int[] eliminateDuplicates(int[] list) {
int newLength = list.length;
// find length w/o duplicates:
for (int i = 1; i < list.length; i++) {
for (int j = 0; j < i; j++) {
if (list[i] == list[j]) { // if duplicate founded then decrease length by 1
newLength--;
break;
}
}
}
int[] newArray = new int[newLength]; // create new array with new length
newArray[0] = list[0]; // 1st element goes to new array
int inx = 1; // index for 2nd element of new array
boolean isDuplicate;
for (int i = 1; i < list.length; i++) {
isDuplicate = false;
for (int j = 0; j < i; j++) {
if (list[i] == list[j]) { // if duplicate founded then change boolean variable and break
isDuplicate = true;
break;
}
}
if (!isDuplicate) { // if it not duplicate then put it to new array
newArray[inx] = list[i];
inx++;
}
}
return newArray;
}
Ответ 4
Возможно, вы можете использовать lambdaj (скачать здесь, website), эта библиотека очень эффективна для управления коллекциями (..list, массивы), следующий код очень прост и отлично работает:
import static ch.lambdaj.Lambda.selectDistinct;
import java.util.Arrays;
import java.util.List;
public class DistinctList {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1,3,4,2,1,5,6,8,8,3,4,5,13);
System.out.println("List with duplicates: " + numbers);
System.out.println("List without duplicates: " + selectDistinct(numbers));
}
}
Этот код показывает:
List with duplicates: [1, 3, 4, 2, 1, 5, 6, 8, 8, 3, 4, 5, 13]
List without duplicates: [1, 2, 3, 4, 5, 6, 8, 13]
В одной строке вы можете получить отдельный список, это простой пример, но с этой библиотекой вы можете разрешить больше.
selectDistinct(numbers)
Вы должны добавить lambdaj-2.4.jar в свой проект. Надеюсь, это будет полезно.
Примечание.. Это поможет вам предположить, что у вас могут быть альтернативы вашему коду.
Ответ 5
public int[] removeRepetativeInteger(int[] list){
if(list.length == 0){
return null;
}
if(list.length == 1){
return list;
}
ArrayList<Integer> numbers = new ArrayList<>();
for(int i = 0; i< list.length; i++){
if (!numbers.contains(list[i])){
numbers.add(list[i]);
}
}
Iterator<Integer> valueIterator = numbers.iterator();
int[] resultArray = new int[numbers.size()];
int i = 0;
while (valueIterator.hasNext()) {
resultArray[i] = valueIterator.next();
i++;
}
return resultArray;
}
Ответ 6
Что вам нужно сделать, вам нужно проверить, что для каждого элемента во втором массиве используется предыдущий элемент или нет.
Вы можете использовать лучший подход. Используйте HashSet и возвращаемый набор.
public static Set removeDuplicates(int []s){
Set<Integer> set = new HashSet<Integer>();
for(int i=0;i<s.length;++i){
set.add(s[i]);
}//endFori
return set;
}//endMethod
Если вам нужен int Array, то посмотрите на это
java-hashsetinteger-to-int-array.
Ответ 7
Вы также можете поместить элементы массива в Set
, для которого семантика точно такова, что он не содержит повторяющихся элементов.
Ответ 8
Попробуйте это
public static int[] removeDuplicates(int[] s) {
Integer[] array = new HashSet<Integer>(Arrays.asList(ArrayUtils.toObject(s))).toArray(new Integer[0]);
return ArrayUtils.toPrimitive(array);
}
Изменить: обновлено с помощью Apache Lang для преобразования в примитивы.
Ответ 9
Итерации по массиву и заполнение набора, поскольку наборы не могут содержать дубликаты. Затем скопируйте элементы из набора в новый массив и верните его. Это показано ниже:
public static int[] removeDuplicates(int[] array) {
// add the ints into a set
Set<Integer> set = new HashSet<Integer>();
for (int i = 0; i < array.length; i++) {
set.add(array[i]);
}
// copy the elements from the set into an array
int[] result = new int[set.size()];
int i = 0;
for (Integer u : set) {
result[i++] = u;
}
return result;
}
Ответ 10
Вы также можете использовать библиотеку Google Guava и использовать ImmutableSet do
ImmutableSet.copyOf(myArray).asList();
Ответ 11
public class Test
static int[] array = {4, 3, 3, 4, 5, 2, 4};
static HashSet list = new HashSet();
public static void main(String ar[])
{
for(int i=0;i<array.length;i++)
{
list.add(array[i]);
}
System.out.println(list);
}}
Выход: [2, 3, 4, 5]
Ответ 12
Но вы можете наивно. Сначала вам нужно отсортировать массив. Вы можете сделать это, используя любой алгоритм сортировки. Я использовал быструю сортировку. А затем проверьте позицию с ее следующей позицией. Если они не совпадают, добавьте значение в новый массив, иначе пропустите эту итерацию.
Пример кода (быстрая сортировка):
public static void quickSort(int[] array, int low, int high) {
int i = low;
int j = high;
int pivot = array[low + (high - low) / 2];
while (i <= j) {
while (array[i] < pivot) i++;
while (array[j] > pivot) j--;
if (i <= j) {
exchange(array, i, j);
i++;
j--;
}
}
if (0 < j) quickSort(array, 0, j);
if (i < high) quickSort(array, i, high);
}
public static void exchange(int[] array, int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
Удалить дубликаты:
public static int[] removeDuplicate(int[] arrays) {
quickSort(arrays, 0, arrays.length - 1);
int[] newArrays = new int[arrays.length];
int count = 0;
for (int i = 0; i < arrays.length - 1; i++) {
if (arrays[i] != arrays[i + 1]) {
newArrays[count] = arrays[i];
count++;
}
}
return newArrays;
}
Ответ 13
Вы можете использовать HashSet, который не позволяет создавать дублирующие элементы
public static void deleteDups(int a []) {
HashSet<Integer> numbers = new HashSet<Integer>();
for(int n : a)
{
numbers.add(n);
}
for(int k : numbers)
{
System.out.println(k);
}
System.out.println(numbers);
}
public static void main(String[] args) {
int a[]={2,3,3,4,4,5,6};
RemoveDuplicate.deleteDups(a);
}
}
o/p is 2
3
4
5
6
[2, 3, 4, 5, 6]
Ответ 14
public class DistinctNumbers{
public static void main(String[] args){
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter ten numbers: ");
int[] numbers = new int[10];
for(int i = 0; i < numbers.length; ++i){
numbers[i] = input.nextInt();
}
System.out.println("The distinct numbers are:");
System.out.println(java.util.Arrays.toString(eliminateDuplicates(numbers)));
}
public static int[] eliminateDuplicates(int[] list){
int[] distinctList = new int[list.length];
boolean isDuplicate = false;
int count = list.length-1;
for(int i = list.length-1; i >= 0; --i){
isDuplicate = false;
for(int j = i-1; j >= 0 && !isDuplicate; --j){
if(list[j] == list[i]){
isDuplicate = true;
}
}
if(!isDuplicate){
distinctList[count--] = list[i];
}
}
int[] out = new int[list.length-count-1];
System.arraycopy(distinctList, count+1, out, 0, list.length-count-1);
return out;
}
}
Ответ 15
Привет всем, что вы можете использовать этот код, который я создаю!!!
import java.util.*;
public class DistinctNumber {
public static void main(String[] args) {
int[] nums= {1,3,2,3,4,3,2,5,4,6};
int [] T2 = duplicate(nums);
for (int i = 0; i < T2.length; i++) {
System.out.println(T2[i]);
}
}
public static boolean exist(int x,int []A){
for (int i = 0; i < A.length; i++) {
if(x==A[i]){
return true;
}
}
return false;
}
public static int [] EliminateDuplicate(int [] numbers){
int [] B = new int[numbers.length];
int i=0,j=0;
for(i=0;i<numbers.length;i++){
if(!exist(numbers[i], B)){
B[j] = numbers[i];
j++;
}
}
int[] C = new int[j];
for (int k = 0; k < C.length; k++) {
C[k] = B[k];
}
return C;
}
}
Ответ 16
Это сработало для меня:
import java.util.Arrays;
import java.util.HashSet;
public class Util {
public static int[] removeDups(final int[] intArrayWithDups) {
final int[] intArrayDupsRemoved = new int[intArrayWithDups.length];
final HashSet<Integer> alreadyAdded = new HashSet<>();
int innerCounter = 0;
for (int integer : intArrayWithDups) {
if (!alreadyAdded.contains(integer)) {
intArrayDupsRemoved[innerCounter] = integer;
alreadyAdded.add(intArrayDupsRemoved[innerCounter]);
innerCounter++;
}
}
return Arrays.copyOf(intArrayDupsRemoved, innerCounter);
}
}
Ответ 17
Вы можете сделать что-то вроде этого
public class MyClass {
public static void main(String args[]) {
int[] man = {4,56,98,89,78,45,78, 79, 56};
for (int i = 0; i < man.length; i++)
{
for (int j = i+1; j < man.length; j++)
{
//check if it is equal
if (man[i] == man[j])
{
man[j] = man[j] -1;
//Decrementing size
j--;
}
}
}
//Array without duplicates
for(int k=0; k<man.length; k++)
{
System.out.print(" " + man[k]);
}
}
}
Ответ 18
Это вопрос интервью. Вопрос: Удалить дубликаты из массива на месте:
public class Solution4 {
public static void main(String[] args) {
int[] a = {1,1,2,3,4,5,6,6,7,8};
int countwithoutDuplicates = lengthofarraywithoutDuplicates(a);
for(int i = 0 ; i < countwithoutDuplicates ; i++) {
System.out.println(a[i] + " ");
}
}
private static int lengthofarraywithoutDuplicates(int[] a) {
int countwithoutDuplicates = 1 ;
for (int i = 1; i < a.length; i++) {
if( a[i] != a[i-1] ) {
a[countwithoutDuplicates++] = a[i];
}//if
}//for
System.out.println("length of array withpout duplicates = >" + countwithoutDuplicates);
return countwithoutDuplicates;
}//lengthofarraywithoutDuplicates
}
В Python:
def lengthwithoutduplicates(nums):
if not nums: return 0
if len(nums) == 1:return 1
# moving backwards from last element i.e.len(a) -1 to first element 0 and step is -1
for i in range(len(nums)-1,0,-1):
# delete the repeated element
if nums[i] == nums[i-1]: del nums[i]
# store the new length of the array without the duplicates in a variable
# and return the variable
l = len(a)
return l
a = [1, 1, 2, 3, 4, 5, 6, 6, 7, 8];
l = lengthwithoutduplicates(a)
for i in range(1,l):print(i)
В Python: понимание списка, используя перечисление
a = [1, 1, 2, 3, 4, 5, 6, 6, 7, 8]
aa = [ ch for i, ch in enumerate(a) if ch not in a[:i] ]
print(aa) # output => [1, 2, 3, 4, 5, 6, 7, 8]
Ответ 19
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
// Remove duplicates from a list of integers
public class IntegerUtils {
public static void main(String[] args) {
int intArray[] = {1, 2, 4, 2, 67, 4, 9};
List<Integer> uniqueList = removeDuplicates(intArray);
uniqueList.stream().forEach(p -> System.out.println(p));
}
public static List<Integer> removeDuplicates(int[] intArray) {
return Arrays.stream(intArray).boxed().distinct().collect(Collectors.toList());
}
}
Ответ 20
попробуй это.
int numbers[] = {1,2,3,4,1,2,3,4,5,1,2,3,4};
numbers = java.util.stream.IntStream.of(numbers).distinct().toArray();
Ответ 21
int[] arrayRemoveDuplicates= Arrays.stream("integerArray").distinct().toArray();
// print the unique array
for (int i = 0; i < arrayRemoveDuplicates.length; i++) {
System.out.println(arrayRemoveDuplicates[i]);
}
Java.util.streamapi введен в Java 8
Ответ 22
import java.util. *;
public class Duplicates {
public static void main(String[] args) {
// TODO Auto-generated method stub
int [] myArray = {1,3,2,4,3,2,3,4,5,6,7,6,5,4,3,4,5,6,76,5,4,3,4,4,5};
List <Integer> myList = new ArrayList <Integer>();
myList = removeDuplicates(myArray);
//Printing Output
for (int k=0; k<myList.size();k++)
System.out.print(" "+ myList.get(k));
}
private static List<Integer> removeDuplicates(int[] myArray) {
// TODO Auto-generated method stub
Arrays.sort(myArray);
List <Integer> myList = new ArrayList <Integer>();
for (int i=0; i<myArray.length-1; i++){
if (myArray[i]!= myArray[i+1]){
myList.add(myArray[i]);
}
}
myList.add(myArray[myArray.length-1]);
return myList;
}
}
Ответ 23
public class Foo {
public static void main(String[] args) {
//example input
int input[] = new int[]{1, 6 , 5896, 5896, 9, 100,7, 1000, 8, 9, 0, 10, 90, 4};
//use list because the size is dynamical can change
List<Integer> result = new ArrayList<Integer>();
for(int i=0; i<input.length; i++)
{
boolean match = false;
for(int j=0; j<result.size(); j++)
{
//if the list contains any input element make match true
if(result.get(j) == input[i])
match = true;
}
//if there is no matching we can add the element to the result list
if(!match)
result.add(input[i]);
}
// Print the result
for(int i=0; i<result.size(); i++)
System.out.print(result.get(i) + ", ");
}
}
выход: 1, 6, 5896, 9, 100, 7, 1000, 8, 0, 10, 90, 4,