Is there any way to avoid mistakes when dealing with array index ?


  • 2
    H

    The problem is simple but easy to make mistake. It took me three submissions to pass and some time working on the bugs which mainly come from the incorrect index counting. I wonder if there is any efficient way to avoid these mistakes in coding rather than testing. Thanks !


  • 0
    B

    For me, it has been improved just by working on more and more problems. For each problem, I run a few corner cases either in my head or using paper & pen.


  • 2
    D

    compare every element with the last two element of new Array(only be stored in the origin array)

    int removeDuplicates(int A[], int n) {
    
        if(n<=2)
           return n;
        int cnt=1;
        for(int i=2;i<n;i++){
            if(A[i]==A[cnt]&&A[i]==A[cnt-1])
                ;
            else
                A[++cnt]=A[i];
        }
        return cnt+1;
     }

  • 0
    S

    The idea is similar to the partition function of qsort, use index l to track the last index of new array(the length of new array is definitely shorter than or equal to the old array). when new element comes, just compare it to the last second element in new array to make sure no three duplicate elements in new array.

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

  • 0
    T
    class Solution {
    public:
        int removeDuplicates(int A[], int n) {
            int N = 1;
            int count = 1;
            for(int i = 1; i < n; ++i) {
                if(A[i] != A[i-1]) {
                    A[N++] = A[i];
                    count = 1;
                }
                else if(A[i] == A[i-1]) {
                    if(count == 1) {
                        count++;
                        A[N++] = A[i];
                    }
                }
            }
            return n == 0 ? 0 : N;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.