https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/
LeetCode - The World's Leading Online Programming Learning Platform
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
Algorithm
처음 index 값을 1로 저장해놓는다.그 후 r 포인터로 반복문을 돌면서 nums[i] 와 nums[i+1] 이 달라진다면 중복된 값이 끝났다는 뜻이므로,nums[index] = nums[i+1] 로 새 값을 넣어준다.
Python
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
l = 1
for r in range(1, len(nums)):
if nums[r] != nums[r-1]:
nums[l] = nums[r]
l += 1
return l
Java
class Solution {
public int removeDuplicates(int[] nums) {
int l = 1;
for(int r=1; r<nums.length; r++){
if(nums[r-1] != nums[r]) {
nums[l++] = nums[r];
}
}
return l;
}
}
'자료구조&알고리즘 > LeetCode' 카테고리의 다른 글
[LeetCode] 1091. Shortest Path in Binary Matrix (0) | 2024.03.21 |
---|---|
[LeetCode] 1171. Remove Zero Sum Consecutive Nodes from Linked List (0) | 2024.03.12 |
[LeetCode] 27. Remove Element (0) | 2023.09.18 |