My C++ code 5ms ,can be more Efficiency ?


  • 0
    D
    enter code here class Solution 
    {
    public:
    int removeElement(int A[], int n, int elem) 
    {
    	int begin = 0 , end = n-1;
    	while(begin <=end)
    	{
    		if(A[begin] == elem)
    		{
    			swap(A[begin],A[end]);
    			--end;
    		}
    		else
    			++begin;
    	}
    	return end + 1;
    }

  • 0

    I guess there can be.
    You don't need to actually swap the values of begin and end.
    You could just asign end to begin. That is faster than the std::swap implementation.


  • 0
    D

    thanks,that is right·.


  • 0
    Q

    int removeElement(int A[], int n, int elem) {
    int j=0;
    for(int i=0;i<n;i++){
    if(A[i]!=elem){
    A[j++]=A[i];
    }
    }
    return j;
    }
    2ms


  • 0
    S

    int removeElement(int A[], int n, int elem) { int j=0; for(int i=0;i<n;i++){ if(A[i]!=elem){ A[j++]=A[i]; } } return j; } - wont work if you have [1 2 3 4 elem 5 elem elem elem 6]
    And it seems like rules have been changed. now you have to return modified array where elem are completely removed. even if its in the end.


Log in to reply
 

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