26. Remove Duplicates from Sorted Array

🔗 Link bài toán: Remove Duplicates from Sorted Array
🔺 Bài toán: Cho một mảng số nguyên nums
đã được sắp xếp tăng dần, hãy loại bỏ các phần tử trùng lặp tại chỗ của chúng. Các phần tử duy nhất phải giữ nguyên thứ tự ban đầu. Trả về số lượng phần tử duy nhất k
trong mảng.
💡 Ý tưởng:
Sử dụng một con trỏ
index
để giữ vị trí cuối cùng của phần tử duy nhất.Duyệt qua mảng
nums
, nếu tại vị tríi
có giá trị khácnums[index]
, tăngindex
và gánnums[index] = nums[i]
.Sau khi duyệt xong, giá trị
index + 1
sẽ là kết quả.
🔧 Solution:
class Solution {
public int removeDuplicates(int[] nums) {
int index = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] != nums[index]) {
nums[++index] = nums[i];
}
}
return index + 1;
}
}
⏱️ Độ phức tạp:
Time complexity: O(n) - Duyệt qua mảng một lần.
Space complexity: O(1) - Không sử dụng bộ nhớ bổ sung.
#leetcode #array
Subscribe to my newsletter
Read articles from Duong Tan Thanh directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
