分享

leetCode 26.Remove Duplicates from Sorted Array(删除数组重复点) 解题思路和方法

 雪柳花明 2016-10-03
Remove Duplicates from Sorted Array
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.

 

思路:此题比较简单,大意是将数组中重复点删除,然后返回新数组的长度。数组中前n个数就是新的数组。唯一难点是不能用额外空间。

详细代码如下:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Solution {
    public int removeDuplicates(int[] nums) {
        if(nums.length <= 1){
            return nums.length;
        }
        int len = 1;//新的长度,至少为1,以下循环从i=1开始
        for(int i = 1; i < nums.length; i++){
            if(nums[i] != nums[i-1]){//不等于前一个元素,长度+1
                nums[len++] = nums[i];//将新的元素装到前len个
            }
        }
        return len;
    }
}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多