LeetCode-从排序数组中删除重复项
给定一个nums按非递减顺序排序的整数数组,就地删除重复项,以便每个唯一元素只出现一次。元素的相对顺序应该保持不变。不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。
自定义判定:
int[] nums = [...]; // Input array
int[] expectedNums = [...]; // The expected answer with correct length
int k = removeDuplicates(nums); // Calls your implementation
assert k == expectedNums.length;
for (int i = 0; i < k; i++) {
assert nums[i] == expectedNums[i];
}
示例1:
Input: nums = [1,1,2]
Output: 2, nums = [1,2,_]
Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).
示例2:
Input: nums = [0,0,1,1,1,2,2,3,3,4]
Output: 5, nums = [0,1,2,3,4,_,_,_,_,_]
Explanation: Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).
分析:
如果传入的数组长度是0,我们就直接返回0;如果不是0,我们先定义一个变量(count),用于返回数组长度,接着我们就对其进行遍历,判断第一个元素与第二个元素是否相等,如果不相等,第一个元素也就成为新数组的第一个元素,接着把数组长度加1,如果相等,我们就继续遍历后面的元素,以此类推。最后把数组的最后一个元素放入新数组里面,把数组长度加一。
代码:
class Solution {
public int removeDuplicates(int[] nums) {
if(nums.length == 0) return 0;
int count = 0;
int i;
for(i = 0;i<nums.length-1;i++){
if(nums[i]!=nums[i+1]){
nums[count] = nums[i];
count++;
}
}
nums[count]=nums[i];
return count+1;
}
}
本文作者:Jack
版权声明:未经授权禁止使用,转载请说明出处!