zoukankan      html  css  js  c++  java
  • 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 A = [1,1,2],

    Your function should return length = 2, and A is now [1,2].

    这道题和上一道题目比較像:Leetcode: Remove Element
    都是通过定义一个伪指针,这个指针记录满足要求的数据位置,当前数据满足要求的时候(不用删除的时候)指针移动一位,最后返回这个伪指针的值。

    C++參考代码:

    class Solution
    {
    public:
        int removeDuplicates(int A[], int n)
        {
            if (n == 0) return 0;
            int pt = 1;
            for (int i = 1; i < n; i++)
            {
                if (A[i - 1] != A[i])
                {
                    A[pt++] = A[i];
                }
            }
            return pt;
        }
    };

    C#參考代码:

    public class Solution
    {
        public int RemoveDuplicates(int[] A)
        {
            if (A.Length == 0) return 0;
            int pt = 1;
            for (int i = 1; i < A.Length; i++)
            {
                if (A[i - 1] != A[i]) A[pt++] = A[i];
            }
            return pt;
        }
    }

    Python參考代码:

    class Solution:
        # @param a list of integers
        # @return an integer
        def removeDuplicates(self, A):
            count = len(A)
            if count == 0:
                return 0
            pt = 1
            for i in range(1, count):
                if A[i - 1] != A[i]:
                    A[pt] = A[i]
                    pt += 1
            return pt

    Java參考代码:

    public class Solution {
        public int removeDuplicates(int[] A) {
            if (A.length == 0) return 0;
            int pt = 1;
            for (int i = 1; i < A.length; i++) {
                if (A[i - 1] != A[i]) {
                    A[pt++] = A[i];
                }
            }
            return pt;
        }
    }

    版权声明:本文博客原创文章,博客,未经同意,不得转载。

  • 相关阅读:
    KnockOut循环绑定
    json数组排序
    1,滑动验证,前后台接口
    写个js程序咖常写的游戏-贪吃蛇
    ionic的路由配置及参数传递
    基于jq, jquery.easie.js 开发面向对象通栏焦点图组件
    面向对象开发弹窗组件
    基于jquery开发的选项卡
    JavaScript多线程 html5 Worker, SharedWorker
    gulp常用任务
  • 原文地址:https://www.cnblogs.com/hrhguanli/p/4713069.html
Copyright © 2011-2022 走看看