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

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.

 

Java

package array;

import java.util.Arrays;

public class RemoveDuplicateDemo {
    public static void main(String[] args) {
        int[] nums1 = {1, 1, 2, 2, 3};
        int length = removeDuplicate(nums1);
        print(length);

        int[] nums2 = new int[length];
        System.arraycopy(nums1, 0, nums2, 0, length);
        print(Arrays.toString(nums2));
    }

    public static int removeDuplicate(int[] nums) {
        if(nums == null || nums.length == 0) {
            return 0;
        }
        int idx = 1;
        int sentinel = nums[0];
        for(int num: nums) {
            if(num != sentinel) {
                nums[idx++] = num;
                sentinel = num;
            }
        }
        return idx;
    }

    public static void print(Object obj) {
        System.out.println(obj);
    }
}

 

Python

# -*- coding: utf-8 -*-


def remove_duplicate(nums):
    if not nums:
        return 0
    sentinel = nums[0]
    idx = 1
    for num in nums:
        if num != sentinel:
            sentinel = num
            nums[idx] = num
            idx += 1
    return idx

nums = [1, 1, 2, 2, 3, 4, 5, 5]
l = remove_duplicate(nums)
print l, nums[:l]

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics