From 54026aeb901936d08cbcf4f419cfbc52a8a1d992 Mon Sep 17 00:00:00 2001 From: hitanshu310 Date: Fri, 3 Jan 2025 21:33:04 +0530 Subject: [PATCH] Adding solution (java) --- .../solution.java | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Remove Duplicates from Sorted Array/solution.java diff --git a/Remove Duplicates from Sorted Array/solution.java b/Remove Duplicates from Sorted Array/solution.java new file mode 100644 index 0000000..acac66c --- /dev/null +++ b/Remove Duplicates from Sorted Array/solution.java @@ -0,0 +1,37 @@ +class Solution { + + public void swap(int[] arr, int ind1, int ind2) { + + int temp = arr[ind1]; + arr[ind1] = arr[ind2]; + arr[ind2] = temp; + + } + + public int removeDuplicates(int[] nums) { + + int unique = 0; + int seek = 0; + + while (seek <= nums.length - 1) { + // Initialize a limit pointer + int limit = seek; + // If limit is already on last element of array, look-ahead should be avoided + // Till numbers repeat increment limit, else break + while (limit < nums.length - 1 && nums[seek] == nums[limit + 1]) { + limit = limit + 1; + } + // Swap the seek pointer value and the unique pointer value, then increment + // unique pointer + swap(nums, seek, unique); + unique = unique + 1; + // Move the seek pointer, only if end of array hasn't been reached + if (limit == nums.length - 1) { + break; + } else { + seek = limit + 1; + } + } + return unique; + } +} \ No newline at end of file