持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第13天。
题目链接: leetcode.com/problems/re…
1. 题目介绍(移除排序数组中的重复元素)
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.
【Translate】: 给定一个按非递减顺序排序的整数数组nums,就地删除重复的元素,使每个惟一元素只出现一次。元素的相对顺序应该保持不变。
Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.
【Translate】: 由于在某些语言中不可能更改数组的长度,因此必须将结果放在数组nums的第一部分。更正式地说,如果在删除重复项之后还有k个元素,那么nums的前k个元素应该保存最终结果。它与前k个元素以外的元素无关。
Return k after placing the final result in the first k slots of nums.
【Translate】: 将最终结果放入nums的前k个槽后返回k。
Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.
【Translate】: 不要为其他数组分配额外的空间。为此,必须使用O(1)额外内存来修改输入数组。
【Custom Judge】:
【测试用例】:
【约束】:
2. 题解
2.1 nicer loops -- O(n)
StefanPochmann所提供的题解 5 lines C++/Java, nicer loops 。不多解释,就是很简单。
public int removeDuplicates(int[] nums) {
int i = nums.length > 0 ? 1 : 0;
for (int n : nums)
if (n > nums[i-1])
nums[i++] = n;
return i;
}