0026_Remove Duplicates from Sorted Array

来源:互联网 发布:js原型链 编辑:程序博客网 时间:2024/05/20 21:44

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.

JAVA

题中要求将不重复的数字挪到数组的前边,并返回不重复的数字部分的长度result,也就是说程序运行之后,nums数组的前result位都要是不重复的数字,但是没要求有序。第一次只返回了result,并没有改变数组中的数据,导致WA,调整后顺利AC,但是效率排在后1/3。。。但是看了下排名靠前的代码,基本想法都是一样的,没分析出来他们快在哪里,还需要再看看。。

public class Solution {    public int removeDuplicates(int[] nums) {        if(nums.length == 0){            return 0;        }        int result = 1;        int targetNum = nums[0];        int index = 1;        int replaceIndex = 1;        while(index < nums.length){            if(nums[index] != targetNum){                ++result;                targetNum = nums[index];                nums[replaceIndex] = nums[index];                ++replaceIndex;            }            ++index;        }        return result;    }}
原创粉丝点击