LeetCode笔记:26. 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.

大意:

给出一个有序数组,移除重复的数字,让每个元素只出现一次,并返回新的长度。

不要分配额外的空间给另一个数组,你必须在固定的内存下去做。

举例:
给出输入的数组为 nums = [1,1,2],

你的函数应该返回长度 = 2,并让前面两个数字为单独的1和2。在新长度之外的位置无所谓你留下了什么内容。

思路:

这道题和LeetCode笔记:27. Remove Element这个很类似,只不过这道题的难度在于,在操作中不能随意改变数组中原本元素的位置,因为你要保持它后面的数字还是有序的,才好去比较相邻的数字是否一样。其实也简单,我们弄一个变量记录上一个单独的数字,再弄一个变量记录该数字后面的位置序号,往后遍历,直到遇到不一样的数字,才把那个数字放到该位置序号来,然后把记录单独数字的变量设为这个新数字,记录位置的变量序号+1,继续往后遍历,因为是随着遍历过程往前放数字,所以不会影响到后面的数字顺序。

代码(Java):

public class Solution {
    public int removeDuplicates(int[] nums) {
        if (nums.length == 0) return 0;
        int position = 1;
        int lastNumber = nums[0];
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] > lastNumber) {
                nums[position] = nums[i];
                position++;
                lastNumber = nums[i];
            }
        }
        return position;
    }
}

合集:https://github.com/Cloudox/LeetCode-Record
版权所有:http://blog.csdn.net/cloudox_

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值