write once,run anywhere
  • Home
  • Tags
  • Archives

LeetCode [26] Remove Duplicates from Sorted Array

Contents

  • Questions
  • Coding
    • python

Questions¶

Difficulty: Easy

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.

Coding¶

python¶

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

class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if nums is None or len(nums) == 0:
            return 0
        elif len(nums) == 1:
            return 1
        else:
            list, i, end = [], 0, len(nums) - 1
            while i <= end:
                if i == end:
                    list.append(nums[i])
                    i += 1
                else:
                    j = i + 1
                    if nums[i] == nums[j]:
                        while j <= end and nums[i] == nums[j]:
                            j += 1
                    list.append(nums[i])
                    i = j
            for i in range(0, list.__len__()):
                nums[i] = list[i]

            return list.__len__()

Related Posts

  • LeetCode [1] Two Sum
  • LeetCode [2] Add Two Numbers
  • LeetCode [58] Length of Last Word
  • LeetCode [190] Reverse Bits
  • LeetCode [151] Reverse Words in a String

  • « LeetCode [7] Reverse Integer
  • LeetCode [58] Length of Last Word »

Published

8月 20, 2016

Last Updated

8月 20, 2016

Category

Linux

Tags

  • LeetCode 13

Contact

  • Powered by Pelican. Theme: Elegant by Talha Mansoor