Leetcode 26 Remove Duplicates
Leetcode 26 Remove Duplicates
题目描述
Remove Duplicates from Sorted Array
Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
For example,
Given input array nums = [1,1,2],
Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn’t matter what you leave beyond the new length.
解题思路
此题亦可以使用插空法,即插入到正确的位置。具体来说的话,当遍历到的元素和插空前的元素进行比较,如果不等于,直接插入,如果相等,则跳过即可。
代码实现
C++版本
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int len_nums = nums.size();
if (len_nums <= 0) {
return 0;
}
int insert_pos = 1;
int i = 1;
while (i < len_nums) {
if (nums[i] != nums[insert_pos - 1]) {
nums[insert_pos++] = nums[i++];
}
else {
++i;
}
}
return insert_pos;
}
};
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
Java版本
public class Solution {
public int removeDuplicates(int[] nums) {
int len = nums.length;
if (len <= 0) {
return 0;
}
int i = 1;
int insert_pos = 1;
while (i < len) {
if (nums[i] != nums[insert_pos - 1]) {
nums[insert_pos++] = nums[i++];
}
else {
++i;
}
}
return insert_pos;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
Python版本
class Solution:
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
len_nums = len(nums)
if len_nums <= 0:
return 0
insert_pos = 1
i = 1
while i < len_nums:
if nums[i] != nums[insert_pos - 1]:
nums[insert_pos] = nums[i]
insert_pos += 1
i += 1
else:
i += 1
return insert_pos
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
文章来源: blog.csdn.net,作者:herosunly,版权归原作者所有,如需转载,请联系作者。
原文链接:blog.csdn.net/herosunly/article/details/86651163
- 点赞
- 收藏
- 关注作者
评论(0)