Remove Duplicates From Sorted Array leetcode java
算法描述:
Given a sorted array, 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 in place with constant memory.
For example,
Given input array 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 new length.
算法分析:一个有序数组,出去其中出现次数大于1的数,返回剩余元素个数
代码:设置两个指针,i 遍历原数组,j 是去除重复后的下标
public int removeDuplicates(int[] nums) { if(nums == null || nums.length == 0) return 0; int len = nums.length; int j = 1; //数组第一个元素是不需要变的,所以长度至少为1 for(int i = 1; i < len; i++){ //数组遍历从下标1开始 if(nums[i] == nums[i - 1]) continue; else { nums[j++] = nums[i]; } } return j; }