题目描述
https://leetcode.com/problems/remove-duplicates-from-sorted-array/
Given a sorted array nums, remove the duplicates in-place such that each element appears only once and returns the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
Clarification:
Confused why the returned value is an integer but your answer is an array?
Note that the input array is passed in by reference, which means a modification to the input array will be known to the caller as well.
Internally you can think of this:
博主第一次提交的代码
这题的不难,但是还是要提升自己写整洁代码的能力,同时思考这题的意义,这题的Clarification内容已经说清楚让你返回整数了,那么原因就是我们不需要删除数组中的元素
image.png
class Solution {
public int removeDuplicates(int[] nums) {
if(nums.length == 0 || nums.length == 1){
return nums.length;
}
int lastDuplicate = nums[0];
int result = 1;
for(int i = 1; i <nums.length;i++){
if(nums[i] != lastDuplicate){
nums[result] = nums[i];
result++;
lastDuplicate = nums[i];
}
}
return result;
}
}
别人优秀的整洁代码
解法一
int count = 0;
for(int i = 1; i < n; i++){
if(A[i] == A[i-1]) count++;
else A[i-count] = A[i];
}
return n-count;
解法二
在我二次反思的过程当中,这个解法还是值得品味一下,在循环的if中,如果需要剔除的数组量级很大,同,'i == 0'与'n > nums[i-1]'的顺序如果调换一下,性能会更高的,因为'i == 0'在量级很大的时候,并且重复率较高的数组中,大概率还是返回false的
public int removeDuplicates(int[] nums) {
int i = 0;
for (int n : nums)
if (i == 0 || n > nums[i-1])
nums[i++] = n;
return i;
}
当然i==0就是担心数组溢出的问题,我们可以将此段保护提前一下
public int removeDuplicates(int[] nums) {
if(nums.length < 2) {
return nums.length;
}
int i = 1;
for (int n : nums)
if (n > nums[i-1])
nums[i++] = n;
return i;
}
网友评论