26. Remove Duplicates from Sorted Array

题目描述:

Given a sorted array, 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 in place with constant memory.

For example, Given input array 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 new length.

题目翻译

给定一个已经排序好的数组,删除重复的元素,得到一个每个元素只显示一次的新数组,返回值为新数组的长度。 不要为另一个数组分配额外的空间,您必须使用常量内存来执行此操作。

例如,

给定输入数组nums = [1,1,2], 您的函数应返回长度2,同时数组被更新为nums = [1,2]。

解题方案

标签: Array

思路:

  • 当数组长度为0或者1时,直接访问长度值即可,不存在重复元素。
  • 如果超过1,则对数组进行遍历,使用index变量指向数组更新位置,i变量指向数组遍历位置。
  • 如果nums[inde] != nums[i]成立,则先移动index,然后更新,否则不更新。
  • 返回值index少加了一次,故而为index+1

代码:

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

results matching ""

    No results matching ""