remove all occurrences of a given value in nums

By   Tewodros   Date Posted: Oct. 13, 2023  Hits: 408   Category:  .NET Core   Total Comment: 0             A+ A-


side

Given an a list of array numbers and an integer value val, remove all occurrences of val in nums without creating a new array. You have to do it in place.  Then return the number of elements in nums which are not equal to val.

Example:

nums = {3,6,3,6,7,3,5,1,9} 

val = 3

Ans: {6,6,7,5,1,9}

count = 6

 

Solution:

 

public class Solution {

    public int RemoveElement(int[] nums, int val) {

        int count = 0;

        int j = 0;

        for(int i=0; i<nums.Length; i++)

        {

            if(nums[i] != val)

            {

                 nums[j] = nums[i];

                count++;

                 j++;

            }          

        }

        return count;

    }

}


Tags



Back to Top



Related Blogs






Please fill all fields that are required and click Add Comment button.

Name:*
Email:*
Comment:*
(Only 2000 char allowed)


Security Code:* zdwikn

Back to Top