oj26. Remove Duplicates from Sorted Array

来源:互联网 发布:网络事件对社会的影响 编辑:程序博客网 时间:2024/05/23 00:00

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,并且前两个元素应依次12。就是将不重复的元素依次排到前面。

思路:设置一个标志来记录插入非重复的角标,初始化为1,判断角标i和i+1的元素是否相等,若不等则nums[flag]=num[i+1],length++;

 public int removeDuplicates(int[] nums) {        int length = 0;        int flag = 1;        if(nums.length != 0) {            length = 1;        }        for(int i = 0;i<nums.length-1;i++){            if(nums[i] != nums[i+1]){            length++;            nums[flag] = nums[i+1];            flag++;            }        }        return length;    }


0 0