##LeetCode—26. Remove Duplicates from Sorted Array
####题目
https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/
给出一个有序数组,要求将将其中重复的数挑出,只剩下不重复的数字,不能增加空间复杂度,,也就是不能新建数组,将不重复的数字排在原数组的前面,返回不重复数字的个数。例如:
Given nums = [1,1,2],
Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.
It doesn't matter what you leave beyond the returned length.
Given nums = [0,0,1,1,1,2,2,3,3,4],
Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.
It doesn't matter what values are set beyond the returned length.
####思路及解法
要注意到,原数组是有序的,也即是重复的数字一定是相邻的。首先要循环遍历数组,找到重复的数字,每找到第一个不重复的数字,就要把这个数放到,数组的前面。我们维护两个指针,一个用来遍历原数组,一个记录新数字放置的位置。另外要注意端点的情况。
####代码
时间复杂度O(n)
空间复杂度O(1)
class Solution {
public int removeDuplicates(int[] nums) {
int len = nums.length;
int j = 0;
for(int i = 1 ; i < len ; i++){
if(nums[i] != nums[i-1]){
j++;
nums[j] = nums[i];
}
}
return j+1;
}
}