LeetCode # Array # Easy # 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.

题目解析:给定一个有序的重复数组,要求你对数组进行修改后,返回一个数组下标,使得该下标前的子数组是没有重复元素的。要求空间复杂度O(1).

思路:不能借助其他数据结构,只能对原数组进行直接修改。定义一个数end,作为数组下标。当遇到不重复的数字,就将数字复制到下标指示的位置,下标再向后移动一位。遍历完整个原数组后,从0开始,长度为end的子数组就是题目要求的。

 1 public class Solution {
 2     public int removeDuplicates(int[] nums) {
 3         if(nums.length <= 1){
 4             return nums.length;
 5         }
 6         int len = 1;//新的长度,至少为1,以下循环从i=1开始
 7         for(int i = 1; i < nums.length; i++){
 8             if(nums[i] != nums[i-1]){//不等于前一个元素,长度+1
 9                 nums[len++] = nums[i];//将新的元素装到前len个,然后len++;
10             }
11         }
12         return len;       
13     }
14 }

 参考:https://www.2cto.com/kf/201507/415691.html

猜你喜欢

转载自www.cnblogs.com/DongPingAn/p/8949540.html