Thursday, July 23, 2015

Remove Element

Problem : Given an array of elements and a value, remove all the instances of that value in place and return the new length. Note : The order of the elements can be changed. It does not matter what you leave beyond the new length. 

Basic idea is to move all the elements to be removed to the end of the array.
1. Run a for loop with two pointers. One starting at the front of the array and another starting at the end of the array. 
2. Move pointer1 toward the end till you encounter a value to be removed. 
3. Move pointer 2 towards the start of the array till you encounter a value not to be removed. 
4. swap both the values. 
5. Count how many elements have been moved to the end and subtract it from the length of the original array to return the new valid length. 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class Solution {
    public int removeElement(int[] nums, int val) {
        int length = nums.length;
        int temp;
        if(length ==0){
            return 0;
        }
        for(int i = 0, j = length-1; i <length; i++, j--){
            while(i < length && nums[i]!= val){
                i++;
            }
            while(j >-1 && nums[j]== val){
                j--;
            }
            if(i <j){
                nums[i]= nums[j];
                nums[j] = val;
            }
           
        }
        int count =0;
        for(int i=0; i <length; i++){
            if(nums[i] == val)
            count++;
        }
        return length-count;
        
    }
}

No comments:

Post a Comment