leetcode: Remove Duplicates from Sorted Array

159 篇文章 0 订阅

问题描述:

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.

原问题链接:https://leetcode.com/problems/remove-duplicates-from-sorted-array/

 

问题分析

  这个问题要求即要调整了数组里重复的元素又要返回有效个元素长度的值。想到一个简单有效的方法有时候需要花一点时间。主要的思路如下。

  在所有元素都相同的情况下,它其实至少也就是有1个有效的元素。所以最开始我们应该设置表示元素个数的变量j为1。我们可以循环遍历数组,从索引1的位置开始。每次和它前面的元素比较,如果这个元素和它前面的元素不同,则nums[j] = nums[i]。同时j要增加1。这种方法相对简单一点。因为它已经针对最开始那个元素设置了1个的数量。可以简化很多复杂的判断。详细的实现见如下代码:

 

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

 

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值