`
frank-liu
  • 浏览: 1666121 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

leetcode: 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.

原问题链接: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;
    }
}

 

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics