【Leetcode-easy】Remove Duplicates from Sorted Array

题目要求:删除排好序的含有重复元素的数组。返回去除重复后的数组长度,并更新原始数组。不能使用额外空间。

思路:要不额外的使用内存空间,那么只有遍历数组,count保持下一个不重复的数字,遍历过程中如果与该不重复数子不同或与上一个数字不同,则该数保存到count位置,并count++。如果相同,则继续遍历。

 1     public int removeDuplicates(int[] nums) {
 2         
 3         if(nums==null||nums.length==0){
 4             return 0;
 5         }
 6         int count=1;
 7         for(int i=1;i<=nums.length-1;i++){
 8             if(nums[count-1]!=nums[i]){
 9                 nums[count]=nums[i];
10                 count++;
11             }
12         }
13         return count;
14     }
原文地址:https://www.cnblogs.com/scecit/p/4991553.html