美文网首页
Remove Duplicates from Sorted Ar

Remove Duplicates from Sorted Ar

作者: Hf1dw | 来源:发表于2018-03-17 12:31 被阅读0次

Question

Analysis

给定一个排序数组,去掉里面重复的元素,并返回新数组的长度。不要为另一个数组分配额外的空间,必须通过使用O(1)额外内存来修改输入数组来实现这一点。

Answer

public int removeDuplicates (int[] nums){
  if (nums.length==0){
    return 0;
  }
  int i=0;
  for (int j=1;j<nums.length;j++){
    if (nums[j]!=nums[i]){
      nums[++i]=nums[j];
    }
  }
  return i+1;
}

相关文章

网友评论

      本文标题:Remove Duplicates from Sorted Ar

      本文链接:https://www.haomeiwen.com/subject/faudqftx.html