[leetcode]26. Remove Duplicates from Sorted Array去除有序数组的重复元素

Given a sorted array nums, 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 by modifying the input array in-place with O(1) extra memory.

Example 1:

Given 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 returned length.

Example 2:

Given nums = [0,0,1,1,1,2,2,3,3,4],

Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.

It doesn't matter what values are set beyond the returned length.

题意:

去除有序数组的重复元素,使得每个元素只能在数组中出现一次

思路:

仍然是在尽量不开新空间的情况下,

直接在原数组中进行操作。

指针i来遍历原数组,若当前i元素不等于前一个相邻元素,送到指针j那里去

指针j 从 index 1 开始, 因为index 为 0 的元素是什么牛鬼蛇神都不重要。j 接收所有指针i送来的去重后的元素。

扫完一遍后

指针j所指的位置就是新“数组”的长度

代码:

 1 class Solution {
 2     public int removeDuplicates(int[] nums) {
 3         if(nums.length == 0) return 0;
 4         int j = 1;
 5         for(int i = 1; i < nums.length; i++){
 6             if(nums[i] != nums[i-1]){
 7                nums[j] = nums[i];
 8                j++;
 9             }
10         }
11       return j;  
12     }
13 }

猜你喜欢

转载自www.cnblogs.com/liuliu5151/p/9125439.html