Remove Duplicates from Sorted Array

来源:互联网 发布:c语言简单游戏程序代码 编辑:程序博客网 时间:2024/06/15 00:58

原题:

Given a sorted array, remove the duplicates in place such that each element appear onlyonce 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 ofnums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length.

即把排好序的数组重复部分删掉,返回没有重复单元的数组长度。


思考过程:

一开始没有比较好的时间复杂度比较小的思路,看来别人的,豁然开朗。


解题思路:

相当于把原数组所有元素拿起来依次放回去。如果发现数组里已经有了当前要放进去的元素,就不放,找下一个。一共两个指针,一个标记手里的元素,一个标记数组里的元素。


结果代码:

public int removeDuplicates(int[] nums) {    int i = 0;    for (int j = 0;j < nums.length;j++)//i和j分别用于标记被赋值的位置和遍历到的位置。    if (nums[j] != nums[i]) nums[++i] = nums[j];    return i + 1;}



原创粉丝点击