• [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].

     解题思路:

    依次从array中寻找新的元素,顺序放到array前端,然后跳过重复元素,寻找新的元素,直到末尾。

    class Solution {
    public:
        int removeDuplicates(int A[], int n) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
            if(n <= 1)
                return n;
            
            int loc = 0, val_loc = 0;
            while(loc < n)
            {
                A[val_loc] = A[loc];
                val_loc++;
                
                int next = n;
                for(int i = loc + 1;i < n;i++)
                {
                    if(A[i] != A[loc])
                    {
                        next = i;
                        break;
                    }
                }
                loc = next;
            }
            return val_loc;
        }
    };
  • 相关阅读:
    MongoDB数据类型
    杭电1257
    杭电1716
    杭电1997
    杭电1492
    杭电1208
    杭电1290
    杭电1087
    杭电1568
    杭电1398
  • 原文地址:https://www.cnblogs.com/changchengxiao/p/3416485.html
Copyright © 2020-2023  润新知