[LeetCode][Java] Remove Duplicates from Sorted Array

来源:互联网 发布:淘宝怎么看卖家信誉 编辑:程序博客网 时间:2024/05/02 00:43

题目:

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,数组中的两个元素分别为1 and 2。数组中的超过这个长度的元素无关紧要。 

算法分析:

利用双指针

 * 前后两个指针,前指针固定不动,后指针去搜索
 * 直到后指针指到与前指针不同的元素上,这时统计到了第二个不同元素,i++;
 * 前指针重置到现在后指针的位置
 * 重复上述过程,能够统计出不同的元素的总个数,而且原数组中的前i个元素即为这i个互为不同的元素

AC代码:

/** * 前后两个指针,前指针固定不动,后指针去搜索 * 直到后指针指到与前指针不同的元素上,这时统计到了第二个不同元素,i++; * 前指针重置到现在后指针的位置 * 重复上述过程,能够统计出不同的元素的总个数,而且原数组中的前i个元素即为这i个互为不同的元素 */ public class Solution {    public int removeDuplicates(int[] nums)     {if(nums.length==0) return 0;int startindex = 0;int endindex = 0;int i=0;    while(endindex<nums.length)    {    while(endindex<nums.length)    {    if(nums[startindex]==nums[endindex])     endindex++;    else    {    break;    }       }    nums[i]= nums[startindex];startindex=endindex;i++;    }return i;    }}


0 0
原创粉丝点击