Remove duplicates from sorted array – Java implementation
Task: given sorted array, remove all duplicates from it, but you can’t create another one.
Solution:
package ua.org.bytes.algorithm; public class RemoveDuplicatesInSortedArray { public static int removeDuplicates(int[] array) { int size = array.length; int leftIndex = 0; int rightIndex = 1; while (rightIndex < size) { if (array[leftIndex] != array[rightIndex++]) { array[++leftIndex] = array[rightIndex]; } else { continue; } } int result = leftIndex++; for (; leftIndex < size; ++leftIndex) { array[leftIndex] = 0; } printArray(array); return result; } private static void printArray(int[] array) { StringBuffer result = new StringBuffer(); result.append("["); for (int i : array) { result.append(i + " "); } result.append("]"); System.out.println(result); } public static void main(String[] args) { System.out.println(removeDuplicates(new int[] { 1, 2, 2, 2, 4 })); System.out.println(removeDuplicates(new int[] { 1, 1, 2, 2, 2, 4, 4, 5, 6, 7, 8, 9, 9, 9 })); } }
My LinkedIn Account
Останні коментарі