26. Remove Duplicates from Sorted Array
Tags:
Easy
Skills:
Array
June 24, 2025
04:32 AM
No headings found
Loading content...
Related Posts
Leetcode
No headings found
Related Posts
Leetcode
Problem
Bài toán yêu cầu loại bỏ các phần tử trùng lặp khỏi một mảng số nguyên đã được sắp xếp tăng dần, thực hiện trực tiếp trên mảng (in-place) và return độ dài mới của mảng chứa các phần tử duy nhất. Các phần tử duy nhất phải nằm ở đầu mảng, thứ tự giữ nguyên
Nhận xét
Vì mảng đã được sắp xếp, các phần tử trùng lặp sẽ nằm cạnh nhau. Ta có thể sử dụng kỹ thuật two pointers
Approach
Solution
1function removeDuplicates(nums: number[]): number {
2 let unique_element_index = 0;
3 for (const curr_element of nums) {
4 if (unique_element_index === 0 || curr_element !== nums[unique_element_index - 1]) {
5 nums[unique_element_index] = curr_element;
6 unique_element_index++
7 }
8 }
9
10 return unique_element_index;
11};