leetCode/src/main/java/com/leetcode/array/RemoveDuplicates.java

58 lines
1.7 KiB
Java
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package com.leetcode.array;
/**
*
* 删除排序数组中的重复项
给定一个排序数组,你需要在 原地 删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。
不要使用额外的数组空间,你必须在 原地 修改输入数组 并在使用 O(1) 额外空间的条件下完成。
 
示例 1:
给定数组 nums = [1,1,2],
函数应该返回新的长度 2, 并且原数组 nums 的前两个元素被修改为 1, 2。
你不需要考虑数组中超出新长度后面的元素。
示例 2:
给定 nums = [0,0,1,1,1,2,2,3,3,4],
函数应该返回新的长度 5, 并且原数组 nums 的前五个元素被修改为 0, 1, 2, 3, 4。
你不需要考虑数组中超出新长度后面的元素。
作者:力扣 (LeetCode)
链接https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/x2gy9m/
来源力扣LeetCode
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
*/
public class RemoveDuplicates {
public int removeDuplicates(int[] nums) {
int idx = 0;
for (int i = 1; i < nums.length; i++) {
if (nums[i-1] != nums[i]) {
idx ++;
nums[idx] = nums[i];
}
}
return idx + 1;
}
public static void main(String[] args) {
int[] nums = {0,0,1,1,1,2,2,3,3,4};
RemoveDuplicates rDuplicates = new RemoveDuplicates();
int res = rDuplicates.removeDuplicates(nums);
System.out.println(res);
for (int i = 0; i < res; i++) {
System.out.print(nums[i] + ",");
}
System.out.println();
}
}