0% completed
Three approaches!
Abdullah AlKheshen
Jun 22, 2024
Sure, here are the three approaches without the main function, focusing solely on the core algorithms:
Approach 1: Using slow_ptr and fast_ptr with Initialization of slow_ptr to 1
class Solution { public: static int removeDuplicates(vector<int> &arr) { int slow_ptr = 1; for (int fast_ptr = 1; fast_ptr < arr.size(); fast_ptr++) { if (arr[slow_ptr - 1] != arr[fast_ptr]) { arr[slow_ptr] = arr[fast_ptr]; slow_ptr++; } } return slow_ptr; } };
Approach 2: Using slow_ptr and fast_ptr with Initialization of slow_ptr to 0
class Solution { public: static int removeDuplicates(vector<int> &nums) { int slow_ptr = 0; for (int fast_ptr = 0; fast_ptr < nums.size(); fast_ptr++) { if (nums[slow_ptr] != nums[fast_ptr]) { slow_ptr++; nums[slow_ptr] = nums[fast_ptr]; } } return slow_ptr + 1; } };
Approach 3: Using slow_ptr and fast_ptr with Initialization of slow_ptr to 1
class Solution { public: static int removeDuplicates(vector<int> &nums) { int slow_ptr = 1; for (int fast_ptr = 1; fast_ptr < nums.size(); fast_ptr++) { if (nums[fast_ptr - 1] != nums[fast_ptr]) { nums[slow_ptr] = nums[fast_ptr]; slow_ptr++; } } return slow_ptr; } };
Explanation:
-
Approach 1: The
slow_ptrstarts at 1, and for eachfast_ptr, it checks if the previous element in theslow_ptris different from the current element atfast_ptr. If they are different, the element atfast_ptris moved toslow_ptrandslow_ptris incremented. -
Approach 2: The
slow_ptrstarts at 0, and for eachfast_ptr, it checks if the current element atslow_ptris different from the current element atfast_ptr. If they are different,slow_ptris incremented, and the element atfast_ptris moved toslow_ptr. Finally, the function returnsslow_ptr + 1sinceslow_ptris zero-based. -
Approach 3: Similar to Approach 1, but
slow_ptrstarts at 1 and the comparison is between the element beforefast_ptrand the current element atfast_ptr. If they are different, the element atfast_ptris moved toslow_ptrandslow_ptris incremented.
0
0
Comments
On this page
Problem Statement
Solution
Algorithm Walkthrough
Code
Complexity Analysis
Time Complexity
Space Complexity