删除排序数组中的重复项

给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。

不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。

   示例:

   给定数组 nums = [1,1,2], 

   函数应该返回新的长度 2, 并且原数组 nums 的前两个元素被修改为 1, 2。 

   你不需要考虑数组中超出新长度后面的元素。

 1 public class Main {
 2 
 3     public static void main(String[] args) {
 4         int len = 0;
 5         int[] nums = {0, 0, 1, 1, 1, 2, 2, 3, 3, 4};
 6         Solution solution = new Solution();
 7         len = solution.removeDuplicates(nums);
 8         System.out.println("len" + len);
 9         for (int i = 0; i < nums.length; i++) {
10             System.out.print(nums[i] + " ");
11         }
12     }
13 }
14 
15 class Solution {
16     public int removeDuplicates(int[] nums) {
17         int count = 1, i = 0, j = 1;
18         if (nums.length <= 1) {
19             return nums.length;
20         } else {
21             for (; i < nums.length; ) {
22                 if (j == nums.length) {
23                     break;
24                 }
25                 if (nums[j] == nums[i]) {
26                     j++;
27                     continue;
28                 } else {
29                     nums[i + 1] = nums[j];
30                     i++;
31                     j++;
32                     count++;
33                 }
34             }
35         }
36         return count;
37     }
38 }


 
原文地址:https://www.cnblogs.com/Onlyou/p/8858002.html