Back to course home
0% completed
Vote For New Content
Two pointers pattern and swap solution
John Snow
Dec 1, 2023
I have another solution just use two pointers pattern and swap 2 elements in that array.
class Solution { public static int remove(int[] arr) { // TODO: Write your code here int n = arr.length; int first = 0; if (n < 2) return 1; int second = 1; while (first < n && second < n) { if (arr[first] != arr[second]) { if (second - first > 1) { int tmp = arr[first + 1]; arr[first + 1] = arr[second]; arr[second] = tmp; } first++; second++; } else { second++; } } return first + 1; } }
1
0
Comments
Comments
On this page
Problem Statement
Try it yourself