Leetcode-26. Remove Duplicates from Sorted Array

来源:互联网 发布:java colortorgb 编辑:程序博客网 时间:2024/04/30 18:44

前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN,mcf171专栏。

博客链接:mcf171的博客

——————————————————————————————

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.

这个题目有点意思,一开始我以为只要返回长度就可以了,结果还要移动数组的元素,移动数组的元素我一开始走入了误区,考虑了非常多复杂的情况,最终灵光一现,发现两个指针,快的把不重复的往前移动就可以了,碰到重复的不移动就可以了。Your runtime beats 46.45% of java submissions.


public class Solution {    public int removeDuplicates(int[] nums) {        if(nums == null) return 0;if(nums.length == 0 ) return 0;int fastPoint = 0;int slowPoint = 0;while(fastPoint < nums.length){if(fastPoint == 0 || (nums[fastPoint] != nums[fastPoint -1])){nums[slowPoint] = nums[fastPoint];slowPoint ++;}fastPoint ++;}return slowPoint;    }}





0 0
原创粉丝点击