Untitled
unknown
plain_text
9 months ago
2.1 kB
17
Indexable
import java.util.Arrays;
import java.util.Scanner;
public class RemoveFromSortedArray {
/**
*This class Takes an integer array nums sorted in non-decreasing order, remove all duplicates in-place so that each unique element appears only once.
* Return the number of unique elements in the array.
* If the number of unique elements be k, then,
* Change the array nums such that the first k elements of nums contain the unique values in the order that they were present originally.
* The remaining elements, as well as the size of the array does not matter in terms of correctness.
* The driver code will assess correctness by printing and checking only the first k elements of the modified array.
* An array sorted in non-decreasing order is an array where every element to the right of an element is either equal to or greater in value than that element.
*
*
* Examples:
* Input: nums = [0, 0, 3, 3, 5, 6]
* Output: 4
* Explanation:
* Resulting array = [0, 3, 5, 6, _, _]
* There are 4 distinct elements in nums and the elements marked as _ can have any value.
*
* Input: nums = [-2, 2, 4, 4, 4, 4, 5, 5]
* Output: 4
* Explanation
* Resulting array = [-2, 2, 4, 5, _, _, _, _]
* There are 4 distinct elements in nums and the elements marked as _ can have any value.
*/
public static int removeDuplicatesFormStortedArray(int[] nums){
int size = 0;
for (int i = 0; i < nums.length -1; i++) {
if (nums[i] != nums[i+1]){
nums[size++] = nums[i];
}
}
nums[size++] = nums[nums.length-1];
return size;
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("ENTER THE SIZE OF ARRAY -> ");
int size = s.nextInt();
System.out.println("ENTER ARRAY ELEMENTS -> ");
int [] arr = new int [size];
for (int i = 0; i < size; i++){
arr[i] = s.nextInt();
}
System.out.println((removeDuplicatesFormStortedArray(arr)));
}
}
Editor is loading...
Leave a Comment