My c code using two pointer in O(n)


  • 2
    W
    int removeElement(int* nums, int numsSize, int val) {
        int pre = 0, post;
        while (pre < numsSize) {
            post = numsSize - 1;
            while (pre < post && nums[pre] != val) 
                pre++;
            while (post > pre && nums[post] == val) {
                post--;
                numsSize--;
            }
            if (pre == post && nums[pre] != val)
                break;
            nums[pre++] = nums[post];
            numsSize--;
        }
        return numsSize;
    }

  • 0
    N

    I structured my C function to shift the remaining numbers over when a number matching 'val' is found.

    This is probably an easy question for someone who's been at it for a while, but did you use the swap method that you did to reduce execution time / resources? I can see obvious disadvantages in execution time when the array size gets large but don't know about resources.

    I can't submit my work but below is my "working" code. Feedback?

    int i, j;
    int count = 0;
    int newLen = numsSize;
    
    if(nums == NULL || numsSize ==0)
    {
    	return 0; //error?
    }
    
    for(i = 0; i<numsSize; i++)
    {
    	if(nums[i] == val)
    	{
    		newLen--;
    		count = i;
    		while(nums[++count] == val){}//find the next non val place
    	 	nums[i] = nums[count];//backfill that value
    		j=i;//leave i alone
    		for(j,count; count<numsSize; count++)
    		{
    			nums[count] = nums[count+1];//slide the other values over
    		}
    	}
    }return newLen; 
    

  • 0
    W

    when u find the next non val place, u should slide the remain values to place where begin from i.
    And also, the newLen should be consided when u find other val place.


Log in to reply
 

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