LeetCode 26 Remove Duplicates from Sorted Array (移除有序数组中重复数字)

时间:2023-03-09 07:13:33
LeetCode 26 Remove Duplicates from Sorted Array (移除有序数组中重复数字)

从有序数组中移除重复数字,并且返回不重复数字的个数
遍历操作: 可以使用新的for循环 for (int n : nums){}
每次进行对比,并且更新第一个遇到不相等的元素的下标为i
对数组进行重新赋值操作
当数组长度大于1时,ans初值为1,当数组长度为0时,返回0
参考代码 :
package leetcode_50;

/***
*
* @author pengfei_zheng
* 移除有序数组中的重复元素
*/
public class Solution26 {
public int removeDuplicates(int[] nums) {
if(nums.length==0) return 0;
int i = 1; for (int n : nums)
if (n > nums[i-1])//满足则说明不重复
nums[i++] = n;//更新i
return i;
}
}