DEV Community

shine
shine

Posted on

[📝LeetCode #26] Remove Duplicates from Sorted Array

🎀 The Problem

Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Then return the number of unique elements in nums.

Example:

Input: nums = [0,0,1,1,1,2,2,3,3,4]
Output: 5, nums = [0,1,2,3,4,,,,,_]

👩‍💻 My Answer

class Solution { public int removeDuplicates(int[] nums) { int index = 0; int current = nums[0]; boolean check = false; for (int i = 1; i < nums.length; i++) { int next = nums[i]; if (check == false && current == next) { index++; check = true; } else if (check == true && current < next) { nums[index] = next; current = next; index++; } else if (check == false && current < next) { index++; current = next; } } if (check == false) index++; return index; } } 
Enter fullscreen mode Exit fullscreen mode

Runtime & Memory

Pro & Con

  • 🔺 Runtime & Memory
  • ✖️ Too long

💋 Ideal Answer

Approach - "Two Pointer"

I redid this problem using the "Two Pointer" approach on my own.

New Code

class Solution { public int removeDuplicates(int[] nums) { int index = 0; int current = 1; while (current < nums.length) { if (nums[current] != nums[index]) { nums[index+1] = nums[current]; index++; } current++; } return index+1; } } 
Enter fullscreen mode Exit fullscreen mode

Redo Runtime & Memory

I have improved the runtime, but how can I improve memory?

💡 What I Learned

  • I think I mastered the "Two Pointers" method.

Top comments (0)