My best C# code, running 390ms? is there any possible way to performance better?


  • 1
    L

    This is the best I can make, is there any better algorithm to run better? Thanks a lot!


    public class Solution {
    public int RemoveElement(int[] A, int elem) {
          int count = 0;
            int n = A.Length;
            for (int i = 0; i < n; ++i)
            {
                if (A[i] != elem)
                {
                    A[count++] = A[i];
                }
            }
            return count;
    }
    

    }


  • 0
    V

    Instead of doing a change when A[i] not equals to element, you can modify to change when A[i] equals to the element. This reduces the run time for sure as we will have only few changes because you will not need to modify every element of the array till its size but only that matches 'elem'.

    For instance, If matches you can replace that element with the last element in that array.

    .....
    		if (A[i] == elem) {
    			count = count + 1;
    			while ((A[i] == A[end]) && end > i) end = end -1; //The elt to be replaced should not be equal to A[i]
    			A[i] = A[end];
    			end = end - 1;
    		}
    ....

  • 0
    V

    Could you post how much the time has been reduced from 390ms ?


Log in to reply
 

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