题目描述:
Given a sorted array nums, 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 by modifying the input array in-place with O(1) extra memory.
Example 1:
Given nums = [1,1, 2],
Your function should return length = 2,with the first two elements of nums being 1 and 2.
题目解释:
给出一组有序数组,去掉重复的数字使得每个元素只出现一次并且返回新的长度。不允许用另一个数组,空间复杂度为1。
解题思路:
1.我的解法。找一个工作索引index;循环遍历数组,当前值如果大于工作索引-1的值,则把当前值替换到工作索引所在的位置,最后返回index即新的数组的长度。
class Solution {
public int removeDuplicates(int[] nums) {
int index = 1;
for(int i = 0;i< nums.length;i++) {
if(nums[i] > nums[index - 1]) {
nums[index] = nums[i];
index++;
}
}
return index;
}
}