Adding solution (java)
This commit is contained in:
parent
3e821a932d
commit
54026aeb90
37
Remove Duplicates from Sorted Array/solution.java
Normal file
37
Remove Duplicates from Sorted Array/solution.java
Normal file
@ -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;
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user